blob: 2c421451a8e5a8d2b90ba4dd489f68240728543d [file] [log] [blame]
Sean Reifscheider78a44c52010-03-19 23:23:05 +00001# Import the email modules we'll need
R David Murray29d1bc02016-09-07 21:15:59 -04002from email.parser import BytesParser, Parser
3from email.policy import default
Sean Reifscheider78a44c52010-03-19 23:23:05 +00004
Berker Peksagf9e3cf12015-02-25 18:14:09 +02005# If the e-mail headers are in a file, uncomment these two lines:
R David Murray29d1bc02016-09-07 21:15:59 -04006# with open(messagefile, 'rb') as fp:
7# headers = BytesParser(policy=default).parse(fp)
Sean Reifscheider78a44c52010-03-19 23:23:05 +00008
R David Murray29d1bc02016-09-07 21:15:59 -04009# 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'
Sean Reifscheider78a44c52010-03-19 23:23:05 +000012 '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:
R David Murray29d1bc02016-09-07 21:15:59 -040018print('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))