import the email modules we ll need from email parser import bytesparser if the email headers are in a file uncomment these two lines with openmessagefile rb as fp headers bytesparserpolicydefault parsefp or for parsing headers in a string this is an uncommon operation use now the header items can be accessed as a dictionary you can also access the parts of the addresses import the email modules we ll need from email parser import bytesparser 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 now the header items can be accessed as a dictionary you can also access the parts of the addresses
from email.parser import Parser
from email.policy import default






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')


print('To: {}'.format(headers['to']))
print('From: {}'.format(headers['from']))
print('Subject: {}'.format(headers['subject']))


print('Recipient username: {}'.format(headers['to'].addresses[0].username))
print('Sender name: {}'.format(headers['from'].addresses[0].display_name))