Python send HTML email with attachment
In this article, you will learn how to send HTML content in the mail with a file attachment using a secure SMTP server in the Python programming language. In the previous article, we mentioned how to send simple mail to multiple recipients using an SMTP mail server. If you are unaware of this basic concept, please read the previous article.
Import SMTP library
To send mail using an SMTP mail server, first import the smtplib module. This module defines an SMTP client session object that helps in sending mail over the internet. The smtplib is a built-in module; we do not need to install it.
import smtplib
Import Email Package
The Python email package is combined with many classes and functions for sending simple to complex MIME text, MIME base, and MIME multipart based mail. The encoder is imported to provide default encodings to MIME class constructors. It accepts only one argument, i.e., the message object to encode. The MIMEBase class always adds a Content-Type header and a MIME version header. The MIMEText is used to create MIME objects of the major type text. And the MIMEMultipart class is a subclass of the MIMEBase class. By using this class, we can call the attach() method for multipart messages.
import email
from email import encoders
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
Create MIMEMultipart object
Here, we have created the following multipart object and set the subject, from mail address, recipient mail address, and file name.
msg = MIMEMultipart("alternative")
msg["Subject"] = "multipart test"
msg["From"] = sender_email
msg["To"] = receiver_email
filename = "document.pdf"
HTML Message Part
Suppose we have the following HTML message part that we want to send in mail.
html = """\
<html>
<body>
<p><b>Python Mail Test</b><br>
This is HTML email with attachment.<br>
Click on <a href="https://www.etutorialspoint.com">Python Resources</a>
for more python articles.
</p>
</body>
</html>
"""
Before sending, first convert these into MIMEText object.
part = MIMEText(html, "html")
Next, add the above HTML/plain-text parts to MIMEMultipart message.
msg.attach(part)
Add Attachment
Next, open the PDF file and add the attachment. We have added the file as application/octet-stream and set the entire message object to payload using the set_payload() method.
with open(filename, "rb") as attachment:
part = MIMEBase("application", "octet-stream")
part.set_payload(attachment.read())
Next, encoded the above parts to send in mail-
encoders.encode_base64(part)
Set headers
To send an attachment in mail, we need to add this in the header of the mail using the add_header() method.
part.add_header(
"Content-Disposition",
"attachment", filename= filename
)
msg.attach(part)
Create SMTP Connection
Here, we have used smtplib.SMTP_SSL() to make SMTP communication over a secure, encrypted SSL channel. The arguments for the SMTP_SSL() method are the SMTP server address and the port number. This requires authentication using client credentials (username and password).
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
server.login(sender_email, password)
server.sendmail(
sender_email, receiver_email, msg.as_string()
)
Complete Code: Python Send HTML Mail with Attachment
Here, we have merged the above-mentioned codes to send the HTML part with an attachment in an e-mail using a secure SSL SMTP connection.
import smtplib, ssl, email
from email import encoders
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
sender_email = "SENDER_EMAIL_ADDRESS"
receiver_email = "RECEIVER_EMAIL_ADDRESS"
password = "PASSWORD"
#Create MIMEMultipart object
msg = MIMEMultipart("alternative")
msg["Subject"] = "multipart test"
msg["From"] = sender_email
msg["To"] = receiver_email
filename = "filename.pdf"
#HTML Message Part
html = """\
<html>
<body>
<p><b>Python Mail Test</b>
<br>
This is HTML email with attachment.<br>
Click on <a href="https://www.etutorialspoint.com">Python Resources</a>
for more python articles.
</p>
</body>
</html>
"""
part = MIMEText(html, "html")
msg.attach(part)
# Add Attachment
with open(filename, "rb") as attachment:
part = MIMEBase("application", "octet-stream")
part.set_payload(attachment.read())
encoders.encode_base64(part)
# Set mail headers
part.add_header(
"Content-Disposition",
"attachment", filename= filename
)
msg.attach(part)
# Create secure SMTP connection and send email
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
server.login(sender_email, password)
server.sendmail(
sender_email, receiver_email, msg.as_string()
)
Related Articles
Convert list to dictionary PythonDictionary inside list Python
Pandas string to datetime
Convert Excel to CSV Python Pandas
Python add list to list
Python Pandas Dataframe to CSV
Python compare two lists
Remove element from list Python
Python iterate list with index
Python program to sum all the numbers in a list
Python print without newline
Python iterate list with index
Python send mail to multiple recipients using SMTP server
How to generate QR Code in Python using PyQRCode
Python programs to check Palindrome strings and numbers
CRUD operations in Python using MYSQL Connector
Fibonacci Series Program in Python
Python File Handler - Create, Read, Write, Access, Lock File
Python convert XML to JSON
Python convert xml to dict
Python convert dict to xml