How to send Emails via Python
I've assumed that sending emails via a CLI would be easy. That might even be the case, but sending them in a way that they actually show up in the receiver's mailbox is quite a different story. After following multiple tutorials and using tools from sendmail
to mailx
, not a single email arrived. Since I wanted to send the mail from within a Python script anyway, I moved on to a Real Python tutorial. This is the snippet they use to send an email.
= 465 # For SSL
=
= # Enter your address
= # Enter receiver address
= # Enter password
=
=
And again, nothing arrived at my preferred receiver protonmail. However, if you try to email to a gmail address, you get a helpful error back.
Our system has detected that this message is not RFC 550-5.7.1 5322
compliant: 'From' header is missing. To reduce the amount of spam sent
to Gmail, this message has been blocked.
This is how the snippet looks after adding the 'From' header:
= 465 # For SSL
=
= # Enter your address
= # Enter receiver address
= # Enter password
# 👇 The string is now a f-string and the 'From' header has been added
= f
=
And voilà , the email arrives at gmail. Again nothing at protonmail, but now it wasn't too hard to guess that it might want a 'To' header.
= 465 # For SSL
=
= # Enter your address
= # Enter receiver address
= # Enter password
# 👇 The 'To' header has been added
= f
=
The Real Python tutorial is from 2018, so chances are that there are better ways to send emails nowadays. After looking through the standard library docs, I think the following snippet is a more idiomatic way to achieve the same thing in 2022. The main difference is that it removes duplication with the help of the EmailMessage
class.
= 465 # For SSL
=
= # Enter your address
= # Enter receiver address
= # Enter password
=
=
=
=
=
=
=
You can find the discussion at this Mastodon post.