Skip to main content

python email merge

Replace 'your_file.csv', standard_email_text, and standard_subject with your actual file path and text. The script reads the CSV file, replaces placeholders in the email text and subject line with the corresponding data, and sends the emails.

  • You need to have Microsoft Outlook installed on your system.
  • This script assumes the CSV file is well-formed and the headers match the placeholders.
  • Python's win32com.client library is used for interacting with Outlook, which is Windows-specific.
import csv
import win32com.client as win32

# Define your standard email text and subject line here
standard_email_text = "Hello _name_,\n\nPlease check this URL: _URL_.\nBest regards."
standard_subject = "Information for _name_"

# Function to send email via Outlook
def send_email(recipient, subject, body):
    outlook = win32.Dispatch('outlook.application')
    mail = outlook.CreateItem(0)
    mail.To = recipient
    mail.Subject = subject
    mail.Body = body
    mail.Send()

# Reading CSV and sending emails
with open('your_file.csv', newline='') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        email_body = standard_email_text
        email_subject = standard_subject

        # Replace placeholders in the email text and subject
        for key in row:
            email_body = email_body.replace(f'_{key}_', row[key])
            email_subject = email_subject.replace(f'_{key}_', row[key])

        # Send the email
        send_email(row['email'], email_subject, email_body)