0

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']
onetwothree
  • 672
  • 1
  • 10
  • 20

1 Answers1

1

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()
elethan
  • 16,408
  • 8
  • 64
  • 87