Table of Contents
Introduction
Are you thinking of creating a newsletter for your application but you don’t know how to send an email in python?
Or did you just want to automate some boring tasks?
Well, whatever the motivation, if you want to learn how to send an email using Python, you are in the right place!
This post will guide you step by step to achieve your goal, from enabling two-factor authentication on your Google account to creating the code.
Google account setup
The first step to be able to send email using Python from a Gmail account is to change some settings of it.
More in details, you need to enable two-step authentication and to generate a dedicated password for this script.
I know it may seem long or complex but you will see that the next sections will guide you through these simple operations.
Enable two-step verification
To enable two-step verification on your Google account you should:
- Open Google account page
- Click on Safety in the menu on the left
- Scroll down until you see the ‘Access to Google’ card
At this point you should see something similar to this:

Once this is done, click on Two-step verification
and follow the wizard. Don’t worry, it’s just a few steps!
When you have finished the procedure, go back to the Access to Google
card and you will see that ‘Two-step verification’ is now set to ‘On’ and that a new option is be present.

At this point we need to create a password to be able to authenticate to the Google account from our Python program and the next section will show you how to do it.
Generate password for app
In the previous section we saw how to enable two-factor verification from a Google account.
This section will instead explain you how to generate a password for an application (our python script).
Once the password has been generated, do not tell anyone and remember to write it down because it will no longer be visible.
This is very important because that password has the same function as the standard password, that is, it allows you to log into the account.

Creating a new password is very simple, just click on Password for apps
, log in and select Other
for the Select app
list.

Other
from the select app listAt this point you just have to enter a name for your application, for example send_email_python
and generate the password.
Save the password and close the modal.
We are now ready to write the Python code for our script!
How to send email using Python
This section will describe the code present in this repository.
This simple script will allow you to send an email using simple Python code from a Gmail account.
The repository contains the following main files:
- send_mail.py: this is the starting point of the program, we will execute this file to run it
- src/csv_reader: this file contains the CSVReader class whose aim is to read a CSV file that contains information about emails
- src/email_sender: it contains the EmailSender class whose aim is to send emails from the Google account
To recap, the send_mail.py script instantiates an object of the CSVReader class that reads the recipients, texts and subjects of the emails to be sent and saves everything in a data structure.
The EmailSender class receives this information and it logs in to the Gmail account and sends all emails.
The next sections will show you how to configure the project and what the Python classes mentioned above look like.
Configuration
In order to send emails from your Gmail account you need to configure a few things.
First of all I suggest you to create a virtualenv and install the required python packages using this command:
pip install -r requirements.txt
if you are in troubles look at this link, here you will find all the answers you are looking for!
The second step is to enter your Gmail account credentials inside an .env
file.
Don’t worry, you will already find a file called .env.sample
in the repository, just rename it by removing the .sample
and enter your credentials.
IMPORTANT!
Remember to enter the password generated by your Google account (see previous section)!
Here is an example:
SENDER_ADDRESS=myemail@gmail.com
SENDER_PASSWORD=12345678910111213141516
Please note that you should insert the email and the password without single or double quotes.
The last configuration step regards the insertion of the emails you want to send in the CSV file.
If you look in the data
folder you will find a file called email_info.csv.sample
.
Also in this case, just rename the file by removing the .sample
and insert your recipients, texts and subjects.
If you open the .sample
file you will already find an example that I report below.
target_email | email_text | email_subject |
---|---|---|
example@gmail.com | This is an example text! | Example subject |
CSVReader class
The CSVReader class is in the src/csv_reader.py
file and is quite simple, in fact it has only one method.
The method is called get_email_info_from_csv
and its purpose is to open the CSV file stored in data/email_info.csv
and save each row (excluding the header) in a list.
def get_email_info_from_csv(self):
"""Open CSV file and store rows in a list"""
print("Reading '{}' file...".format(self.csv_path))
email_info_list = []
# open CSV file
with open(self.csv_path, "r") as read_obj:
csv_reader = csv.reader(read_obj)
for idx, row in enumerate(csv_reader):
# skip header
if idx == 0:
continue
# store row in list
email_info_list.append(row)
return email_info_list
If you are not familiar with reading CSV files, I suggest you read this post, here you will find all the information you need.
EmailSender class
The EmailSender class is in the src/email_sender.py
file and logs in to the Google account and sends the emails read from the CSV file.
Once all the emails have been sent, you are logged out.
The EmailSender class contains 3 methods which are:
- server_login
- send_email
- server_logout
The next sections explain all the methods, but let’s start now with the __init__ method.
__init__ method
In the init method, thanks to the python package dotenv
, the account credentials are read from the .env file and stored in environment variables. They are then saved in self.sender and self.password class variables.
If the credentials are present, they are used to log in via the server_login function.
self.sender = os.getenv('SENDER_ADDRESS')
self.password = os.getenv('SENDER_PASSWORD')
if not self.sender or not self.password:
raise ValueError("Missing sender or password, please check .env file.")
# do the login
self.session = self.server_login()
server_login method
The login method uses a Python module called smtplib.
session = smtplib.SMTP_SSL(host="smtp.gmail.com", port=465)
session.login(user=self.sender, password=self.password)
As you can see from the code, the login is done using the host smtp.gmail.com
and the port 465
.
send_email method
The send_email
method receives a parameter that corresponds to the list of rows of the CSV that has read the CSVReader class.
First of all, we extract the recipient, the text and the subject using a for loop on this list.
for email_info in email_info_list:
target_email = email_info[0]
email_text = email_info[1]
email_subject = email_info[2]
Then, the creation of the email with the collected data takes place.
msg = MIMEText(email_text, "html")
msg["Subject"] = email_subject
msg["From"] = self.sender
msg["To"] = target_email
Last but not least, we can finally send the email using the .sendmail method.
self.session.sendmail(self.sender, target_email, msg.as_string())
server_logout method
The logout method simply ends the smtp session.
self.session.quit()
Run the program
To run this Python program simply activate the virtualenv and run the following command:
python send_mail.py
Conclusion
In this post we have configured a Google account to be able to send an email (one or more) using a program written in Python.
I hope this post is useful to you and remember to leave me feedback in the comments.
For any problem do not hesitate to contact me, I will be happy to help you!