How to send email using Python with SMTPLIB and Gmail
Modern web applications often send emails like contact us query, a report or an OTP to a user. In a previous article, we explored NodeJS send email tutorial with MySQL and nodemailer but in this article you will learn how to send email with python using SMTPLIB and Gmail.
Following steps are performed in this tutorial.
1. Set up Gmail account and generate app password
2. Send Text email using Python
3. Send HTML email with Python
4. Adding attachments with Python
5. Run the Script
Send Text email using Python
SMTP protocol is used send emails. To send an email using python, we need a SMTP server. Python client will act as SMTP client and we will use a Gmail test account to send email. This will be easier to configure. You can create a new Gmail account because some settings would be changed to test so it is not a good idea to change your main account settings.
Setting Gmail account for sending email
- Open your newly created Gmail account
- Click on You username on Top right corner
- Click on the link Manage My Account
- When the page opens, Click on Security
- Next, click on 2 step verification
- Follow the steps to switch on 2 step verification
Click on Turn on button.
After the 2 step verification is on, click on App Passwords
Next, select app and click on Other(Custom name).
After selecting the app, Add the name for app. Add name as Send email using Python.
Click on Generate button.
Finally, copy the generated password and click on done.
Send email using Python script
Open your favorite IDE and type the code below.
import smtplib from email.message import EmailMessage email = EmailMessage() email['from'] = 'Programmer Blog - Python <youremail@gmail.com>' email['to'] = 'yourdestinationemail@gmail.com' email['subject'] = 'Welcome to Python!' email.set_content('Wow! Hello World. This email is sent using Python, SMTPLIB and Gmail SMTP') with smtplib.SMTP(host='smtp.gmail.com', port=587) as smtp: smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.login('youremail@gmail.com', 'your_app_password') smtp.send_message(email) print('The mail was sent!')
First, smtplib module is imported. smtplib module is used to define SMTP client session object that is used to send mail to any machine on internet with an SMTP listener daemon.
from email.message import EmailMessage
line is used to import email module that is used for sending emails. The next lines as given below set the from address. (this should be the email that you have used get app password in gmail settings.
email['from'] = 'Programmer Blog - Python <youremail@gmail.com>' email['to'] = 'yourdestinationemail@gmail.com' email['subject'] = 'Welcome to Python!' email.set_content('Wow! Hello World. This email is sent using Python, SMTPLIB and Gmail SMTP')
Th email[‘to’] parameter is set to destination email address where you want to send the email. Next line sets the subject of the email. email.set_content method is used to set the body of the email to receiver.
with smtplib.SMTP(host='smtp.gmail.com', port=587) as smtp: smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.login('youremail@gmail.com', 'your_app_password') smtp.send_message(email) print('The mail was sent!')
Run the script to send email
Open the command prompt, go to project directory and type command below
Note: Before running the script Please make sure to add your app email address, app password, From and Destination email addresses in the script.
python .\send_email.py
If you see any error message as shown below.
ModuleNotFoundError: No module named 'Mail'
Run the command.
After success, You can see a message
If you check your inbox the email is received.
2. Send HTML email with Python
To send a beautiful email with images and links, we can send an HTML email using python.
- Create a new file send_html_email.py
- Create a file template.html.
- Add the HTML code provided in the GitHub link.
Add the code below into the send_html_email.py file.
import smtplib from email.message import EmailMessage from pathlib import Path html_content = Path('template.html').read_text() email = EmailMessage() email['from'] = 'thinkingwebco@gmail.com' email['to'] = 'programmerblog.net@gmail.com' email['subject'] = 'Welcome to Python!' email.set_content(html_content, 'html') with smtplib.SMTP(host='smtp.gmail.com', port=587) as smtp: smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.login('thinkingwebco@gmail.com', 'jqqeonvzhzbhfblr') smtp.send_message(email) print('The mail was sent!')
A new line to import pathlib is added and the HTML content is read form the file using Path method’s read_text method. Inside set_content method the html content is et with ‘html’ type as second parameter.
from pathlib import Path html_content = Path('template.html').read_text()
Change the line email.set_content(...)
to
email.set_content(html_content, 'html')
Run the script to send HTML email
Open the command prompt, go to project directory and type command below
python .\send_html_email.py
You can see a message
If you check your inbox the email is received.
3. Adding attachments to the email with Python
Many times we need to attach documents like PDFs, images and pictures with email. Let’s do it in Python. The emails that contains attachments other than text and html are of type MIME or Multipurpose Internet Mail Extensions. The MIME message are handled by Python’s email.mime module.
import smtplib from email.message import EmailMessage from pathlib import Path from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email import encoders html_content = Path('template.html').read_text() email = MIMEMultipart() email['from'] = 'fromemail@gmail.com' email['to'] = 'thedestinationemail@gmail.com' email['subject'] = 'Welcome to Python email using SMTPLib!' email.attach(MIMEText(html_content, 'html')) filename = 'sample.pdf' with open(filename, 'rb') as attachment: part = MIMEBase('application', 'octet-stream') part.set_payload(attachment.read()) encoders.encode_base64(part) part.add_header("Content-Disposition", f'attachment;filename={filename}') email.attach(part) with smtplib.SMTP(host='smtp.gmail.com', port=587) as smtp: smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.login('fromemail@gmail.com', 'jqqeonvzhzbhfblr') smtp.send_message(email) print('The mail with attachment was sent successfully!')
First, we need to import the modules below.
from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText
Now, as the SMTP is a text only protocol. It means that even if we send binary files like images or PDF files those files will be converted to printable ASCII characters before transport. The most common protocol that is used to convert binary data to ASCII and vice versa is base64. So, from email we will import encoders.
from email import encoders
It is used to convert attachments to ASCII format using base64. In this example the email type will be of type MIME multipart instead of a simple email message. The email object will be of type MIMEMultipart.
email = MIMEMultipart()
Next, instead of using set_content method, the email.attach method is used, where the html content inside MIMEText method is passed. Sample.pdf file is copied into the working directory.
This file will be attached to the email as attachment.
filename = 'sample.pdf' with open(filename, 'rb') as attachment: part = MIMEBase('application', 'octet-stream') part.set_payload(attachment.read()) part.add_header("Content-Disposition", f'attachment;filename={filename}') email.attach(part)
The file name is assigned to the variable filename and the open method is used to open the file in readonly and binary mode using rb parameter. Next, an object of MIMEbase is created and the attachment is set as payload. In the MIMEBase first argument is application and second is octet-stream. The content type application octet-stream means that MIME attachment is a binary file.
The attachment.read() method is used to read the attachment in set_payload method. The part object is encoded into ASCII using encoders‘s encode_based64 method. Hheader is also added using part.add header method. Finally, file is attached to email using email.attach method.
Run the script
To run this script and send an email with attachment using Python, type the command below.
You can see the message on command line.
Source code of the script
You can clone or download source code of the project from the GitHub repository.
Learning Python
Summary
To sum up, in this tutorial you have learned to send email using python and smtplib and Gmail. First, a text email was sent. The HTML email is sent using a HTML template and content type as ‘html‘. The email with attachment can be sent by specifying the email type to MIME and attaching a sample PDF as a base64 encoded binary file. The source code of the tutorial can be found at the GitHub repository.
Related Article
- How to parse xml using python
- How to join wav audio files using python – a beginner tutorial
- Upload files using Python and Flask
- How to make a python password generator
- NodeJS send email tutorial with MySQL and nodemailer
Previous Article
Next Article