Python Automation — How to Send Personalised Emails With Python
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 Allow less secure apps to ON 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.

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 csvfrom 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 csvfrom string import Templatefrom email.mime.multipart import MIMEMultipart
from email.mime.text import MIMETextdef 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 = ‘**********@gmail.com’
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.