17
votes

I'm having some issues trying to extract all the email headers in python. I know how to get the ones I'm looking for but I want to save all the headers and I'm not sure how to do that.

I have it loaded into a email object

import email
f = open(kwargs['opt_emailfile'])
msg = email.message_from_file(f)
f.close()

So I can get

msg['To']
msg['From']

But I want all the headers

Solution

Here is what I did thanks to the answer

        f = open(kwargs['opt_emailfile'])
        msg = email.message_from_file(f)
        f.close()

        parser = email.parser.HeaderParser()
        headers = parser.parsestr(msg.as_string())

        for h in headers.items():
            print h
1
What have you tried so far? Do you have some partially working, or non-working code? - srgerg
ok edited my post to what i have so far - Mike
Not sure if this will help anyone, but here's my two bits. All I had to do (for one specific header) was msg['Header_Name'], and if the header exists, you get the contents, otherwise you get none. - Have a nice day

1 Answers

24
votes

Using HeaderParser perhaps:

from email.parser import HeaderParser
parser = HeaderParser()
h = parser.parsestr(email)

print h.keys()

I just noticed you edited your question. You can actually get the same information from what you had without using HeaderParser. e.g. headers.items() will return list of 2-tuples with headers and corresponding values.