I did not like how messy it is to do this thing with SMTP and email libs so I decided to solve this on my own and created a nicer library for sending emails. You can include a Matplotlib figure as an attachment or in the HTML body without any effort:
# Create a figure
import matplotlib.pyplot as plt
fig = plt.figure()
plt.plot([1,2,3,2,3])
from redmail import EmailSender
# Configure the sender (pass user_name and password if needed)
email = EmailSender(host="<SMTP HOST>", port=0)
# Send an email
email.send(
subject="A plot",
sender="me@example.com",
receivers=["you@example.com"],
# A plot in body
html="""
<h1>A plot</h1>
{{ embedded_plot }}
""",
body_images={
"embedded_plot": fig
},
# Or plot as an attachment
attachments={
"attached_plot.png": fig
}
)
The library (hopefully) should be all you need from an email sender. You can install it from PyPI:
pip install redmail
Documentation: https://red-mail.readthedocs.io/en/latest/
Source code: https://github.com/Miksus/red-mail