mirror of
https://github.com/python/cpython
synced 2024-09-04 15:56:13 +00:00
![R David Murray](/assets/img/avatar_default.png)
This is a wholesale reorganization and editing of the email documentation to make the new API the standard one, and the old API the 'legacy' one. The default is still the compat32 policy, for backward compatibility. We will change that eventually.
25 lines
950 B
Python
25 lines
950 B
Python
# Import the email modules we'll need
|
|
from email.parser import BytesParser, Parser
|
|
from email.policy import default
|
|
|
|
# If the e-mail headers are in a file, uncomment these two lines:
|
|
# with open(messagefile, 'rb') as fp:
|
|
# headers = BytesParser(policy=default).parse(fp)
|
|
|
|
# Or for parsing headers in a string (this is an uncommon operation), use:
|
|
headers = Parser(policy=default).parsestr(
|
|
'From: Foo Bar <user@example.com>\n'
|
|
'To: <someone_else@example.com>\n'
|
|
'Subject: Test message\n'
|
|
'\n'
|
|
'Body would go here\n')
|
|
|
|
# Now the header items can be accessed as a dictionary:
|
|
print('To: {}'.format(headers['to']))
|
|
print('From: {}'.format(headers['from']))
|
|
print('Subject: {}'.format(headers['subject']))
|
|
|
|
# You can also access the parts of the addresses:
|
|
print('Recipient username: {}'.format(headers['to'].addresses[0].username))
|
|
print('Sender name: {}'.format(headers['from'].addresses[0].display_name))
|