python email merge

What it does 

 

 Reads data from a CSV file. 

 Uses the column named "email" from teh CSV file as the to: address. 

 Replaces placeholders in the email text and subject line with corresponding data from the CSV file. 

 Sends each customized email through Microsoft Outlook. 

 

 How it works 

 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. 

 What you need 

 

 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. 

 @Line 28 the standard Excel delimiter is specified, this is depending on local settings and is either , or ; 

 

 Example 

 

 If the body text contains _index_ , _name_ , _ leeg_ or _URL_ these are replaced with the values in the corresponding lines. The search and replace is case-sensitive! 

 Set Outlook to work offline and check the email in the outbox before going back online! 

 Python Script 

 import csv

import win32com.client as win32

import sys

# Define your standard email text and subject line here

standard_email_text = """Beste _name_,

Hierbij de persoonlijke link waarmee u de voortgang van _name_ kan volgen:\n_URL_.

Voor het afronden van de studie binnen drie jaar, moeten dit schooljaar 8 blokken worden afgerond.

Groet, ...............

(deze email is automatisch gegenereerd)

"""

standard_subject = "voortgangsmonitor _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('ouderemailC23 .csv', newline='', encoding='utf-8-sig') as csvfile:

 reader = csv.DictReader(csvfile, delimiter=';')

 for row in reader:

 if ( row['email'] == "" ): # no email, skip

 continue

 email_body = standard_email_text

 email_subject = standard_subject

 email_to = row['email']

 # 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])

 print(f"To: {email_to}")

 print(f"Subject: {email_subject}")

 print(f"{email_body}\n")

 print("-----------------------------------------\n")

 # Send the email

 send_email(row['email'], email_subject, email_body)