onetwothree
onetwothree

Reputation: 682

How can I fetch the SMTP headers after sending email?

I'm able to send emails using smtplib with ease. What I'm struggling with is reading the actual headers that were sent one. Specifically, I'm looking to read the Message-ID and References.

I thought at first that sendmail() would return them, but it does not.

Found that I'm able to redirect smtpilb.stderr to my own function and parse out the data that I need. Is there a better way that would allow me to do say:

headers['References']

Upvotes: 0

Views: 185

Answers (1)

elethan
elethan

Reputation: 16993

If you use sendmail() I am not sure how to access the headers, because you don't have a Message object in that case. However, if you use send_message instead - which is very similar to sendmail() - and pass it an email.message.Message object, then all of the email message headers and their values are stored in a dict in your Message object. So e.g., Message-ID can be accessed from an email message object msg with msg['Message-ID'], subject can be accessed using msg['Subject'], etc. I don't think anything will be stored in message-id unless you put it there yourself though. You can 'roll your own' Message-ID using make_msgid() from email.utils:

from email.utils import make_msgid

msg['Message-ID'] = make_msgid()

Upvotes: 1

Related Questions