Python Send Email To Multiple Contact In CSV File With Personalized Content Example

This article will tell you how to send email to multiple contacts which are saved in a csv file, and how to use email subject and content template 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 represent one row in the csv file. And the list item is a python dictionary object, the dictionary object keys are the row column name and the key mapped value is the related row 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 email to the email address saved in the row data.

1. Example Python Source Code.

python send email to multiple contacts in csv file eclipse source files

Below are the example python code. The python file name is SendToMultiContactsInCSVFileWithPersonalizeContent.py, it’s name is a little bit longer.

'''
Created on Dec 27, 2018

@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 = '[email protected]'
    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 above python source code file.

READ :   How To Make A Website With Python And Django

csv_contacts.csv

Name,Email,Month
Jerry,[email protected],12
Admin,[email protected],11

3. How To Execute This Example.

To execute this example, you can follow below steps.

  1. Setup a local email SMTP server, please refer article How To Connect Localhost Apache James With Thunderbird to setup Apache James in your local machine.
  2. Run this example in eclipse with PyDev plugin, please refer article How To Run Python In Eclipse With PyDev.
  3. To learn more about send email source code in python, please refer Python Send Plain Text, Html Content, Attached Files, Embedded Images Email Example.
  4. To learn more about operate csv file in Python, please refer Python Read/Write CSV File Example.
  5. When i run this example in my environment, i get below email in Thunderbird email client tool.
    personalized email subject and content in thunderbird
(Visited 32 times, 1 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.