This article will tell you how to send emails to multiple contacts which are saved in a CSV file, and how to use email subject and content templates to make the email content personalized in Python.
There are mainly two steps in this example, the first step is to read user contacts in a CSV file and return a list object. One list item represents one row in the CSV file. And the list item is a python dictionary object, the dictionary object keys are the row’s column name and the key mapped value is the related row’s column value.
After you read out all row data in the CSV file, then you should process the second step. Loop in the row list data and send an email to the email address saved in the row’s data.
1. Example Python Source Code.
- Below are the example Python code files.
email |-csv_contacts.csv |-Pop3ReceiveEmail.py |-SendEmail.py |-SendToMultiContactsInCSVFileWithPersonalizeContent.py
- The python file name is SendToMultiContactsInCSVFileWithPersonalizeContent.py, it’s name is a little bit longer. Below is the example python file source code.
''' @author: zhaosong This example will show you how to read multiple contacts email address from csv file and then send email to each contact with personalized email subject and content. ''' import csv from email.header import Header from email.mime.text import MIMEText import smtplib email_subject_template = '''{name} Monthly Billing Report.''' email_content_template = '''Hello {name}, this is your bank billing report email for month {month}.''' def send_email_to_multiple_contact_in_csv_file_with_personalized_content(smtp_server_domain, smtp_server_port, from_addr, csv_file_path): # get all rows in the csv file and return a list. csv_row_list = read_multiple_contacts_from_csv_file(csv_file_path) # loop in the csv rows list and send email. for row_dict in csv_row_list: # parse out required column values from the dictionary object. to_name = '' to_addr = '' to_month = '' # loop in row keys(csv column names). for csv_column_name in row_dict.keys(): # csv column value. column_value = row_dict[csv_column_name] # assign column value to related variable. if csv_column_name.lower() == 'name': to_name = column_value elif csv_column_name.lower() == 'email': to_addr = column_value elif csv_column_name.lower() == 'month': to_month = column_value # create personalized email content with the parsed out personal data. email_subject = email_subject_template.format(name=to_name) email_data = email_content_template.format(name=to_name, month=to_month) send_email(smtp_server_domain, smtp_server_port, from_addr, to_addr, email_subject, email_data) # this method mainly focus on send the email. def send_email(smtp_server_domain, smtp_server_port, from_addr, to_addr, email_subject, email_data): # create MIMEText object and specify the email content as plain text format. msg = MIMEText(email_data, 'plain', 'utf-8') # set email from, to attribute value to display them in the email client tool( thunderbird, outlook etc. ). msg['From'] = from_addr msg['To'] = to_addr msg['Subject'] = Header(email_subject, 'utf-8').encode() # create SMTP server object which will be used to send email. smtp_server = smtplib.SMTP(smtp_server_domain, smtp_server_port) # send the email to specified SMTP server. smtp_server.send_message(msg, from_addr, to_addr) print('Send plain text email complete.') ''' read the csv file content and return a list object, the list object contains all row data of the csv file. each list object item is a dictionary object, the dictionary object represent one row data in csv file. the dictionary object's key is the column name and related value is same row's column value. ''' def read_multiple_contacts_from_csv_file(csv_file_path): csv_rows_list = [] try: # open the csv file. file_object = open(csv_file_path, 'r') # create a csv.DictReader object with above file object. csv_file_dict_reader = csv.DictReader(file_object) # get column names list in the csv file. column_names = csv_file_dict_reader.fieldnames # loop in csv rows. for row in csv_file_dict_reader: # create a dictionary object to store the row column name value pair. tmp_row_dict = {} # loop in the row column names list. for column_name in column_names: # get column value in this row. Convert to string to avoid type convert error. column_value = str(row[column_name]) tmp_row_dict[column_name] = column_value csv_rows_list.append(tmp_row_dict) except FileNotFoundError: print(csv_file_path + " not found.") finally: print("csv_rows_list = " + csv_rows_list.__repr__()) return csv_rows_list if __name__ == '__main__': smtp_server_domain = 'smtp.test.com' smtp_server_port = 25 from_addr = 'admin@test.com' csv_file_path = '/home/zhaosong/WorkSpace/Work/dev2qa.com-example-code/PythonExampleProject/com/dev2qa/example/email/csv_contacts.csv' send_email_to_multiple_contact_in_csv_file_with_personalized_content(smtp_server_domain, smtp_server_port, from_addr, csv_file_path)
2. Example CSV File Data.
- The contacts CSV file should be saved in the same directory as the above python source code file.
- The CSV file name is csv_contacts.csv, below is the CSV file content.
Name,Email,Month Jerry,jerry@test.com,12 Admin,admin@test.com,11
3. How To Execute This Example.
- To execute this example, you can follow the below steps.
- Setup a local email SMTP server, please refer article How To Connect Localhost Apache James With Thunderbird to set up Apache James in your local machine.
- Run this example in eclipse with PyDev plugin, please refer article How To Run Python In Eclipse With PyDev.
- To learn more about sending email source code in python, please refer to Python Send Plain Text, Html Content, Attached Files, Embedded Images Email Example.
- To learn more about operating CSV files in Python, please refer Python Read/Write CSV File Example.
- When I run this example in my environment, I get the below email in the Thunderbird email client tool.