DEV Community

Brad
Brad

Posted on

Complete Email Automation in Python: Bulk Sending, Auto-Reply, and Scheduling

Email automation saves time. Here is a complete Python email system - no paid tools needed.

Send with Attachments

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import os

class EmailBot:
    def __init__(self, gmail_address, app_password):
        self.email = gmail_address
        self.password = app_password

    def send(self, to, subject, html_body, attachments=None):
        msg = MIMEMultipart()
        msg["Subject"] = subject
        msg["From"] = self.email
        msg["To"] = to
        msg.attach(MIMEText(html_body, "html"))

        for f in (attachments or []):
            with open(f, "rb") as fp:
                part = MIMEBase("application", "octet-stream")
                part.set_payload(fp.read())
                encoders.encode_base64(part)
                part.add_header("Content-Disposition", f"attachment; filename={os.path.basename(f)}")
                msg.attach(part)

        with smtplib.SMTP_SSL("smtp.gmail.com", 465) as s:
            s.login(self.email, self.password)
            s.send_message(msg)
Enter fullscreen mode Exit fullscreen mode

Bulk Personalized Campaigns

import csv, time

def bulk_send(bot, csv_file, subject_template, body_template, delay=2):
    sent = 0
    with open(csv_file) as f:
        for row in csv.DictReader(f):
            try:
                bot.send(
                    to=row["email"],
                    subject=subject_template.format(**row),
                    html_body=body_template.format(**row)
                )
                sent += 1
                time.sleep(delay)
            except Exception as e:
                print(f"Failed {row["email"]}: {e}")
    return sent

bot = EmailBot("you@gmail.com", "app-password")
sent = bulk_send(
    bot,
    "leads.csv",
    "Question about {company}",
    "Hi {first_name}, I saw your role for {position}..."
)
print(f"Sent: {sent}")
Enter fullscreen mode Exit fullscreen mode

Read Inbox and Auto-Reply

import imaplib, email

def auto_reply(gmail, password, keyword, reply_body):
    mail = imaplib.IMAP4_SSL("imap.gmail.com")
    mail.login(gmail, password)
    mail.select("inbox")

    _, nums = mail.search(None, "UNSEEN")
    for num in nums[0].split():
        _, data = mail.fetch(num, "(RFC822)")
        msg = email.message_from_bytes(data[0][1])

        if keyword.lower() in (msg["Subject"] or "").lower():
            sender = msg["From"]
            bot = EmailBot(gmail, password)
            bot.send(sender, "Re: " + msg["Subject"], reply_body)
            print(f"Auto-replied to {sender}")
Enter fullscreen mode Exit fullscreen mode

Schedule Weekly Emails

import schedule, time

bot = EmailBot("you@gmail.com", "password")

def weekly_tip():
    bot.send("list@domain.com", "Weekly Python Tip", "This week: save 2h with this script...")

schedule.every().monday.at("09:00").do(weekly_tip)
while True:
    schedule.run_pending()
    time.sleep(60)
Enter fullscreen mode Exit fullscreen mode

Want all these + 45 more automation scripts?

Python Business Automation Toolkit - \ one-time purchase.

What email task takes most of your time? Comment below!

Top comments (0)