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