Sending mails in Python seems simple. It has a built-in library for creating and sending mails (email
, smtplib
). The Internet is awash with tutorials, StackOverflow overflows (ahem) with desperate users looking for answers.
But.
StackOverflow is useful, but the platform is also full of simply bad or outdated examples. And this is especially the case when sending mails.
The main reason: The email
library both contains email.message.Message and email.message.EmailMessage. All StackOverflow samples I found use Message
to deal with emails. Turns out, Message
is legacy (policy: compat32
) reaching back to Python 3.2 - and it lacks many convenient methods to handle mails. Since we already reached the astronomic level of Python 3.11 it’s time to ditch such legacy and provide examples using EmailMessage
. Strangely, I found few to none examples on the Internet at the time I needed it, with the impression that users simply copypaste code without thinking (yes, we’re all guilty).
Sending Mails the Modern Way
Here’s the solution I implemented, abbreviated and lacking error handling for clarity, in the hope that others find it useful and do not fall back to legacy libraries. I heavily relied on the examples provided in the email
library itself - many thanks to the authors, because otherwise I would have been lost.
|
|
That’s it - the simplest working example. The mail is sent in plaintext, since I did not explicitly define a MIME type.
Attachments and a Converter
Two further code snippets come in handy. Here’s how to add an original mail as attachment. Note that the MIME type is, strangely, application/octet-stream
. Googling reveals that there’s no MIME type defined for emails sent as attachments. Again omitting error handling for clarity.
|
|
You can choose the filename
to be whatever you want, usually it’s the subject of the original mail.
Often, libraries or applications will return a Message
object, in my case pytest-localserver. Since you want to be a modern Pythonista, you need to convert it to an EmailMessage
. Here’s the code:
|
|
Image courtesy of Nightcafe and Dall-E.
Last modified on 2022-11-09
Comments Disabled.