Join us
@sofiatarhonska ă» Sep 26,2022 ă» 2 min read ă» 1549 views ă» Originally posted on mailtrap.io
In most cases, you need to add some formatting, links, or images to your email notifications. We can simply put all of these with the HTML content. For this purpose, Python has an email package.
We will deal with the MIME message type, which is able to combine HTML and plain text. In Python, it is handled by the email.mime module.
It is better to write a text version and an HTML version separately, and then merge them with the MIMEMultipart(âalternativeâ) instance. It means that such a message has two rendering options accordingly. In case an HTML isnât be rendered successfully for some reason, a text version will still be available.
Input:
Output:
Sending emails with attachments in Python
The next step in mastering sending emails with Python is attaching files. Attachments are still the MIME objects but we need to encode them with the base64 module. A couple of important points about the attachments:
In transactional emails, the PDF files are the most frequently used: we usually get receipts, tickets, boarding passes, orders confirmations, etc. So letâs review how to send a boarding pass as a PDF file.
Input:
To attach several files, you can call the message.attach() method several times.
Images, even if they are a part of the message body, are attachments as well. There are three types of them: CID attachments (embedded as a MIME object), base64 images (inline embedding), and linked images. We have described their peculiarities, pros and cons, and compatibility with most email clients in this post.
Letâs jump to examples.
For adding a CID attachment, we will create a MIME multipart message with MIMEImage component:
Output:
The CID image is shown both as a part of the HTML message and as an attachment. Messages with this image type are often considered spam: check the Analytics tab in Mailtrap to see the spam rate and recommendations on its improvement. Many email clients  â Gmail in particular â donât display CID images in most cases. So letâs review how to embed a base64 encoded image.
Here we will use base64 module and experiment with the same image file:
Output:
Now the image is embedded into the HTML message and is not available as attached file. Python has encoded our jpg image, and if we go to the HTML Source tab, we will see the long image data string in the img src.
To learn about sending to multiple recipients, using SMTP and Gmail head to the comprehensive guide on sending emails in Python by Mailtrap.
Join other developers and claim your FAUN account now!
Influence
Total Hits
Posts
Only registered users can post comments. Please, login or signup.