Python Automation — How to Send Personalised Emails With Python

Madhumitha Kannan
Sep 11, 2020 · 4 min read

Sometimes, we might be in a situation where we have to send emails to multiple people in a personalised manner (like mailing each student their grades, mailing bank statements to customers, etc.). Although these emails follow the same format, the information inside it varies from receiver to receiver. When done manually, it is time-consuming and there is a lot of room for error. Python allows us to automate this process very easily, let’s see how it’s done.

For this, you will need:

1.A Gmail account for development

2. template.txt file — containing the format for the email body

3. details.csv file — CSV file containing details of the recipients

4. app.py — the python script

1. Gmail account for development

As the python script will access the Gmail account the send out emails, we need to turn in that account. This makes it easier for others to gain access to your account. Hence it is recommended to set up a dummy account/temporary account for this purpose.

2. template.txt file

This text file contains the format for the email body. The personal details from the details.csv file are each placed in the placeholder defined by ‘${}’ in this text file.

Dear ${PERSON_NAME},
You have secured the following marks in your mid-term exams:
Math - ${MATH}
English - ${ENG}
Science - ${SCI}

3. details.csv file

The details.csv/details.xlsx file contains the details that must populate the placeholders in the template file. It contains the details that must be sent to the recipients.it can be an excel file or CSV file.

Here is an example of the details file — contains the student details of the marks they secured in their midterm exams in each subject.

4. The python script

After we have the CSV file and the template file ready, it is now time to write the python script.

i. Import the necessary modules

import smtplib
import csv
from string import Templatefrom email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

ii. Function to read the template.txt file

This function returns the template object containing the contents of the template.txt file.

def read_template(filename):
with open(filename, ‘r’, encoding=’utf-8') as template_file:
template_file_content = template_file.read()
return Template(template_file_content)

iii. Set up the SMTP server

Next, we set up an SMTP connection with the Gmail account using .starttls().

Its isn’t a good practice to include the account address, password in the script if you are going to share this script with others. Instead, use input() to let the user type in their password when running the script.

 MY_ADDRESS = *********@gmail.com  #your gmail account address
PASSWORD = *********** #your password
s = smtplib.SMTP(host=’smtp.gmail.com’, port=587)
s.starttls()
s.login(MY_ADDRESS, PASSWORD)

iv. Construct the email body

  • Loop through the CSV file and create a message for each row in the CSV file.
  • Create a message using MIMEMultipart() function, substitute the details (from each row) in the template to form the message body and save it to the message variable.
  • Next, set up the parameters such as from and to address, message subject. Attach the message variable to the message body.
  • At last, send the message via the send_message() function.
# read the message template
message_template = read_template(‘template.txt’)
with open(“details.csv”, “r”) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=’,’)
# skip the first row as it is the header
next(csv_reader)
for row in csv_reader:
msg = MIMEMultipart() # create a message
# add in the actual person name to the message template
message=
message_template.substitute(PERSON_NAME=row[0],MATH=row[2],
ENG=row[3],SCI=row[4])

# Prints out the message body for our sake
print(message)
# setup the parameters of the message
msg[‘From’]=MY_ADDRESS
msg[‘To’]=lines[1]
msg[‘Subject’]=”Mid term grades”
# add in the message body
msg.attach(MIMEText(message, ‘plain’))
# send the message via the server set up earlier.
s.send_message(msg)
del msg

# Terminate the SMTP session and close the connection
s.quit()

Finally, do not forget to close the SMTP connection after sending all the messages.

The final code

import smtplib
import csv
from string import Templatefrom email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def read_template(filename):
with open(filename, ‘r’, encoding=’utf-8') as template_file:
template_file_content = template_file.read()
return Template(template_file_content)
def main():
message_template = read_template(‘template.txt’)
MY_ADDRESS = ‘
PASSWORD = ‘*************’
# set up the SMTP server
s = smtplib.SMTP(host=’smtp.gmail.com’, port=587)
s.starttls()
s.login(MY_ADDRESS, PASSWORD)

with open(“details.csv”, “r”) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=’,’)
# the below statement will skip the first row
next(csv_reader)
for lines in csv_reader:
msg = MIMEMultipart() # create a message
# add in the actual person name to the message template
message = message_template.substitute(PERSON_NAME=row[0],MATH=row[2],
ENG=row[3],SCI=row[4])
print(message)
# setup the parameters of the message
msg[‘From’]=MY_ADDRESS
msg[‘To’]=lines[1]
msg[‘Subject’]=”Mid term grades”
# add in the message body
msg.attach(MIMEText(message, ‘plain’))
# send the message via the server set up earlier.
s.send_message(msg)
del msg

# Terminate the SMTP session and close the connection
s.quit()
if __name__ == ‘__main__’:
main()

There you have it! Now you can send a lot of emails with personal details within a few seconds.

The Startup

Get smarter at building your thing. Join The Startup’s +785K followers.

Sign up for Top 10 Stories

By The Startup

Get smarter at building your thing. Subscribe to receive The Startup's top 10 most read stories — delivered straight into your inbox, once a week. 

By signing up, you will create a Medium account if you don’t already have one. Review our for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

Madhumitha Kannan

Written by

I’m a Computer Science Undergrad on a quest to innovate and build stuff with code. Find all my posts at https://madhumithakannan.github.io/blog

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +785K followers.

Madhumitha Kannan

Written by

I’m a Computer Science Undergrad on a quest to innovate and build stuff with code. Find all my posts at https://madhumithakannan.github.io/blog

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +785K followers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface.

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox.

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store