Sean Reifscheider | 78a44c5 | 2010-03-19 23:23:05 +0000 | [diff] [blame] | 1 | # Import the email modules we'll need |
R David Murray | 29d1bc0 | 2016-09-07 21:15:59 -0400 | [diff] [blame] | 2 | from email.parser import BytesParser, Parser |
| 3 | from email.policy import default |
Sean Reifscheider | 78a44c5 | 2010-03-19 23:23:05 +0000 | [diff] [blame] | 4 | |
Berker Peksag | f9e3cf1 | 2015-02-25 18:14:09 +0200 | [diff] [blame] | 5 | # If the e-mail headers are in a file, uncomment these two lines: |
R David Murray | 29d1bc0 | 2016-09-07 21:15:59 -0400 | [diff] [blame] | 6 | # with open(messagefile, 'rb') as fp: |
| 7 | # headers = BytesParser(policy=default).parse(fp) |
Sean Reifscheider | 78a44c5 | 2010-03-19 23:23:05 +0000 | [diff] [blame] | 8 | |
R David Murray | 29d1bc0 | 2016-09-07 21:15:59 -0400 | [diff] [blame] | 9 | # Or for parsing headers in a string (this is an uncommon operation), use: |
| 10 | headers = Parser(policy=default).parsestr( |
| 11 | 'From: Foo Bar <user@example.com>\n' |
Sean Reifscheider | 78a44c5 | 2010-03-19 23:23:05 +0000 | [diff] [blame] | 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: |
R David Murray | 29d1bc0 | 2016-09-07 21:15:59 -0400 | [diff] [blame] | 18 | print('To: {}'.format(headers['to'])) |
| 19 | print('From: {}'.format(headers['from'])) |
| 20 | print('Subject: {}'.format(headers['subject'])) |
| 21 | |
| 22 | # You can also access the parts of the addresses: |
| 23 | print('Recipient username: {}'.format(headers['to'].addresses[0].username)) |
| 24 | print('Sender name: {}'.format(headers['from'].addresses[0].display_name)) |