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