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