mkrecny
mkrecny

Reputation: 503

'To' field when parsing email in Python

I'm using the python standard library's email module to parse email. Something like this allows me to determine sender:

msg = email.message_from_string(data)
sender = msg.get_unixfrom()

But I'm having trouble determining who the mail is for.

Thoughts?

Upvotes: 0

Views: 1778

Answers (4)

eks
eks

Reputation: 26

You can always use the __getitem__(name) where name is the name of the header field you want to retrieve; in this case "To", "Cc" and "Bcc".

more information is available at: http://docs.python.org/library/email.message.html

Upvotes: 0

gimel
gimel

Reputation: 86392

Example interactive session:

>>> import email
>>> msg = email.message_from_string("from: me\nto: you\n\nTest\n")
>>> msg.get_all('to')
['you']
>>> msg['to']
'you'
>>> 

Upvotes: 1

AndiDog
AndiDog

Reputation: 70148

You can access all headers of the message by index, e.g. msg["From"]. In the case of the recipient, use msg.get_all("To") because there might be multiple values.

Also note the following:

Headers are stored and returned in case-preserving form but are matched case-insensitively.

Upvotes: 6

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798784

email.message.Message.get_all() will get all values for the given header name.

print msg.get_all('to')

Upvotes: 0

Related Questions