DEV Community

Brad
Brad

Posted on

Python Email Automation: Send 100 Personalized Emails in Minutes

Python Email Automation: Send 100 Personalized Emails in Minutes

Tired of copying and pasting to send personalized emails? Python can automate this completely.

Why Automate Email Sending?

Manual email personalization is time-consuming and error-prone. Python fixes that.

The Complete Email Automation Script

import smtplib
import csv
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from string import Template
import time

def send_personalized_emails(csv_file, template, smtp_config):
    server = smtplib.SMTP(smtp_config['host'], smtp_config['port'])
    server.starttls()
    server.login(smtp_config['user'], smtp_config['password'])

    sent = 0
    with open(csv_file, 'r') as f:
        reader = csv.DictReader(f)
        for row in reader:
            subject = Template(template['subject']).safe_substitute(row)
            body = Template(template['body']).safe_substitute(row)

            msg = MIMEMultipart()
            msg['From'] = smtp_config['user']
            msg['To'] = row['email']
            msg['Subject'] = subject
            msg.attach(MIMEText(body, 'html'))

            server.send_message(msg)
            sent += 1
            print(f'Sent to {row["email"]}')
            time.sleep(1)

    server.quit()
    return sent

# Template with variables
template = {
    'subject': 'Hi $name - Quick note',
    'body': '<p>Hi $name,</p><p>I noticed $company is growing. Want to chat?</p>'
}

smtp_config = {
    'host': 'smtp.gmail.com', 'port': 587,
    'user': 'your@gmail.com', 'password': 'your-app-password'
}

count = send_personalized_emails('contacts.csv', template, smtp_config)
print(f'Sent {count} emails')
Enter fullscreen mode Exit fullscreen mode

CSV Format

name,email,company
John Smith,john@company.com,Acme Corp
Jane Doe,jane@startup.io,StartupIO
Enter fullscreen mode Exit fullscreen mode

Schedule for Optimal Send Time

import schedule
import time

schedule.every().monday.at('10:00').do(lambda: send_personalized_emails('contacts.csv', template, smtp_config))

while True:
    schedule.run_pending()
    time.sleep(60)
Enter fullscreen mode Exit fullscreen mode

Real Results

Using this with 500 contacts: 8 minutes total, 3.2% response rate (vs 1.1% manual).

Gmail App Password Setup

  1. Google Account > Security > App Passwords
  2. Generate for "Mail"
  3. Use as smtp_config['password']

Want the Complete Toolkit?

This is part of the Python Business Automation Toolkit — $9 for email automation + invoice generation + file scripts + web scraping.

What would you automate first? Comment below!

Top comments (0)