Search code examples
pythonemail-parsing

What fields are available after parsing an email message?


I am using email.message_from_string to parse an email message into Python. The documentation doesn't seem to say what standard fields there are.

How do I know what fields are available to read from, such as msg['to'], msg['from'], etc.? Can I still find this if I don't have an email message to experiment with on the command line?


Solution

  • email.message_from_string() just parses the headers from the email. Using keys() you get all present headers from the email.

    import email
    
    e = """Sender: [email protected]
    From: [email protected]
    HelloWorld: test
    
    test email
    """
    
    a = email.message_from_string(e)
    
    print a.keys()
    

    Outputs: ['Sender', 'From', 'HelloWorld']

    Therefore, you will never find a manual that includes from, to, sender etc. as they are not part of the API, but just parsed from the headers.