24 – Real-World Python Projects – Automated Email Sender

🎯 Project Objective

To automate sending personalized emails using Python β€” ideal for newsletters, notifications, or reports.


🧩 1. Overview

Automated emails are used in almost every business β€” from confirmation messages to marketing campaigns.

πŸ’Ό Real-World Use Cases

  • Sending automated invoices or payment reminders
  • Emailing daily reports from a script
  • Sending marketing or newsletter campaigns
  • Notifying users about system alerts or status updates

βš™οΈ 2. Required Libraries

We’ll use built-in and common modules:

  • smtplib β†’ To send emails
  • email.mime β†’ To format messages (text, HTML, attachments)
  • pandas β†’ To read contact lists from CSV

βœ… Auto-install if missing

import subprocess, sys

def install(package):
    try:
        __import__(package)
    except ImportError:
        subprocess.check_call([sys.executable, "-m", "pip", "install", package])

install("pandas")

πŸ“¬ 3. Basic Email Sending

import smtplib
from email.mime.text import MIMEText

def send_basic_email(sender, password, recipient, subject, message):
    msg = MIMEText(message, "plain")
    msg["From"] = sender
    msg["To"] = recipient
    msg["Subject"] = subject

    with smtplib.SMTP("smtp.gmail.com", 587) as server:
        server.starttls()
        server.login(sender, password)
        server.send_message(msg)
        print(f"βœ… Email sent successfully to {recipient}")

πŸ§ͺ Example:

send_basic_email(
    "youremail@gmail.com",
    "your_app_password",
    "friend@example.com",
    "Python Automation Test",
    "This email was sent automatically using Python!"
)

⚠️ Tip:
If you’re using Gmail, you must use an App Password, not your regular password.


πŸ’Œ 4. Send HTML Emails

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def send_html_email(sender, password, recipient, subject):
    html_content = """
    <html>
    <body>
        <h2 style="color:blue;">Hello from Python!</h2>
        <p>This is an <b>automated HTML email</b> with styled content.</p>
    </body>
    </html>
    """

    msg = MIMEMultipart("alternative")
    msg["From"] = sender
    msg["To"] = recipient
    msg["Subject"] = subject
    msg.attach(MIMEText(html_content, "html"))

    with smtplib.SMTP("smtp.gmail.com", 587) as server:
        server.starttls()
        server.login(sender, password)
        server.send_message(msg)
        print(f"βœ… HTML Email sent to {recipient}")

πŸ“Ž 5. Send Emails with Attachments

from email.mime.base import MIMEBase
from email import encoders

def send_email_with_attachment(sender, password, recipient, subject, body, file_path):
    msg = MIMEMultipart()
    msg["From"] = sender
    msg["To"] = recipient
    msg["Subject"] = subject

    msg.attach(MIMEText(body, "plain"))

    # Attach file
    with open(file_path, "rb") as f:
        part = MIMEBase("application", "octet-stream")
        part.set_payload(f.read())

    encoders.encode_base64(part)
    part.add_header("Content-Disposition", f"attachment; filename={file_path}")
    msg.attach(part)

    with smtplib.SMTP("smtp.gmail.com", 587) as server:
        server.starttls()
        server.login(sender, password)
        server.send_message(msg)
        print(f"βœ… Email with attachment sent to {recipient}")

πŸ§ͺ Example:

send_email_with_attachment(
    "youremail@gmail.com",
    "your_app_password",
    "client@example.com",
    "Monthly Report",
    "Please find the attached report.",
    "report.pdf"
)

πŸ“Š 6. Send Bulk Emails from CSV

import pandas as pd

def send_bulk_emails(sender, password, csv_file, subject, message):
    contacts = pd.read_csv(csv_file)

    for index, row in contacts.iterrows():
        recipient = row["email"]
        personalized_message = message.replace("{name}", row["name"])
        send_basic_email(sender, password, recipient, subject, personalized_message)

πŸ§ͺ Example:

# contacts.csv:
# name,email
# John,john@example.com
# Sara,sara@example.com

send_bulk_emails(
    "youremail@gmail.com",
    "your_app_password",
    "contacts.csv",
    "Hello from Python!",
    "Dear {name},\n\nThis is a personalized email sent automatically."
)

βœ… Each contact gets a personalized email automatically!


🧰 7. Interactive Menu for the Toolkit

def main():
    print("\nπŸ“§ Python Automated Email Sender")
    print("1. Send Basic Email")
    print("2. Send HTML Email")
    print("3. Send Email with Attachment")
    print("4. Send Bulk Emails from CSV")
    print("5. Exit")

    choice = input("Enter choice: ")

    sender = input("Enter your email: ")
    password = input("Enter your app password: ")

    if choice == "1":
        recipient = input("Recipient email: ")
        subject = input("Subject: ")
        body = input("Message: ")
        send_basic_email(sender, password, recipient, subject, body)

    elif choice == "2":
        recipient = input("Recipient email: ")
        subject = input("Subject: ")
        send_html_email(sender, password, recipient, subject)

    elif choice == "3":
        recipient = input("Recipient email: ")
        subject = input("Subject: ")
        body = input("Message: ")
        file_path = input("Attachment file path: ")
        send_email_with_attachment(sender, password, recipient, subject, body, file_path)

    elif choice == "4":
        csv_file = input("Enter contacts CSV file path: ")
        subject = input("Email Subject: ")
        message = input("Email Message (use {name} for personalization): ")
        send_bulk_emails(sender, password, csv_file, subject, message)

    elif choice == "5":
        print("πŸ‘‹ Exiting Email Sender.")
if __name__ == "__main__":
    main()

βš™οΈ 8. Best Practices

βœ… Use App Passwords for Gmail security
βœ… Don’t spam or send too many emails quickly β€” use time.sleep() between sends
βœ… Use environment variables for credentials (os.environ)
βœ… Store templates for professional formatting


πŸ’‘ 9. Enhancement Ideas

FeatureDescription
πŸ–₯ GUIAdd a Tkinter interface for email input
πŸ“† SchedulerAutomate daily or weekly email sending
🧾 HTML TemplatesUse stored HTML templates for formatted emails
🧠 AI IntegrationGenerate smart subject lines using OpenAI or text APIs
☁️ Cloud SupportSend attachments from Google Drive or Dropbox

βœ… Summary

FeatureFunction
πŸ“¬ Basic EmailSend plain text messages
πŸ’Œ HTML EmailSend rich formatted emails
πŸ“Ž AttachmentAttach files automatically
πŸ‘₯ Bulk EmailSend personalized messages from CSV
βš™οΈ AutomationCan run daily with cron/task scheduler

Comments

Leave a Reply

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