• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Import the email modules we'll need
2#from email.parser import BytesParser
3from email.parser import Parser
4from email.policy import default
5
6# If the e-mail headers are in a file, uncomment these two lines:
7# with open(messagefile, 'rb') as fp:
8#     headers = BytesParser(policy=default).parse(fp)
9
10#  Or for parsing headers in a string (this is an uncommon operation), use:
11headers = Parser(policy=default).parsestr(
12        'From: Foo Bar <user@example.com>\n'
13        'To: <someone_else@example.com>\n'
14        'Subject: Test message\n'
15        '\n'
16        'Body would go here\n')
17
18#  Now the header items can be accessed as a dictionary:
19print('To: {}'.format(headers['to']))
20print('From: {}'.format(headers['from']))
21print('Subject: {}'.format(headers['subject']))
22
23# You can also access the parts of the addresses:
24print('Recipient username: {}'.format(headers['to'].addresses[0].username))
25print('Sender name: {}'.format(headers['from'].addresses[0].display_name))
26