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