(root)/
Python-3.12.0/
Doc/
includes/
email-headers.py
       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 <user@example.com>\n'
      13          'To: <someone_else@example.com>\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))