AI & Python #11: How to Automate Emails with Python
A quick guide to automate boring emails with Python.
Do you know what most office jobs have in common? In most of them, you have to send emails regularly.
It doesn't matter if youâre a programmer, data scientist, or engineer, chances are you have to read and respond to emails on a daily basis. This activity doesnât add any value to our professions, yet it stops our workflow and takes our valuable time.
The solution? Automate it with Python!
In this guide, Iâll show you how to automate sending emails with Python. Weâll be using Gmail in this tutorial, so make sure you have a Gmail account to test out this automation.
1. Turn On 2-Step Verification
Before we start writing code, we need to set up our Gmail account to be able to use it with Python.
In the past, we could easily connect to Gmail with Python by turning on âLess secure app accessâ but that option isnât available anymore. What we have to do now is turn on 2-step verification to get a 16-character password that we can use to log in to Gmail using Python.
First, go to your Google account, choose the account you want to use for this tutorial, and on the left panel select the option âSecurity.â
Then scroll down until you find the section âSigning in to Google.â Here we need to click on â2-Step Verification.â
After this, weâll see a new page. We have to click on âGet Startedâ
Google will ask to log in again. Then we have to introduce a phone number and click on âNext.â Weâll get a code to verify our phone number. After we introduce the code, we should see the following page.
We need to click on âTurn On.â
If everything was set up correctly, weâll see a new page with the message â2-Step Verification is On.â
Finally, we need to go to the âApp Passwordsâ section, so go to your Google account again, click on âSecurity,â scroll down until you find the section âSigning in to Googleâ and select âApp Passwords.â
We need to log in again. After that, we should see the page below.
In the âSelect appâ dropdown, select âOther (Custom name)â and type any name you want. Iâll name mine âPythonâ and then click on âGenerateâ
After this, we should see a new page with the 16-character password inside a yellow box as shown below.
Itâs all set! Weâll use this 16-character password to log into our Gmail account with Python.
Now you can either copy this password and paste it inside a variable in your Python script or hide the password using environment variables.
2. Send Email with Python
Once we turn on 2-step verification and have our 16-character password, we can start writing code.
Import the libraries and set email sender and receiver
To send emails with Python, we need to use the following built-in Python libraries.
import smtplib
import ssl
from email.message import EmailMessage
email_sender = 'codelessearnmore@gmail.com'
email_password = 'write-password-here'
email_receiver = 'write-email-receiver-here'Also, we set the email sender and password (this is the email we used to turn on 2-step verification) and also the email receiver.
Note that the email receiver doesnât have to be a Gmail account, but can be from a different email service.
Set the subject and body of the email
Now we need to define a subject and a body. We can write anything we want here.
subject = 'Check out my new video!'
body = """
I've just published a new video on YouTube!
"""Note that I open triple quotes in the body to write multiple lines.
After this, we instantiate the EmailMessage class and use the variables we previously created for the emails, subject, and body.
em = EmailMessage()
em['From'] = email_sender
em['To'] = email_receiver
em['Subject'] = subject
em.set_content(body)Add SSL
Now letâs use SSL to add a layer of security. SSL is the standard technology for keeping an internet connection secure and safeguarding any sensitive data that is being sent between two systems.
context = ssl.create_default_context()Log in and send the email
Finally, we specify the hostsmtp.gmail.com, connect through port 465 and use the context defined in the previous step to log in and send our email.
with smtplib.SMTP_SSL('smtp.gmail.com', 465, context=context) as smtp:
smtp.login(email_sender, email_password)
smtp.sendmail(email_sender, email_receiver, em.as_string())Congratulations! Weâve just sent an email using Python. Go to the email_receiver inbox to see the email weâve sent.
Hereâs the email I got.
You can check out the script weâve built in this guide on my Github.
Note: If after running the script you get a ssl.SSLCertVerificationError, search a file named Install Certificates.command and install it. To do so, go to âApplicationsâ, click on a folder named âPython 3.X,â and double click on the file Install Certificates.command.
Once the installation is done, you shouldnât get any error message when running the script.










