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.