π― 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 emailsemail.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
| Feature | Description |
|---|---|
| π₯ GUI | Add a Tkinter interface for email input |
| π Scheduler | Automate daily or weekly email sending |
| π§Ύ HTML Templates | Use stored HTML templates for formatted emails |
| π§ AI Integration | Generate smart subject lines using OpenAI or text APIs |
| βοΈ Cloud Support | Send attachments from Google Drive or Dropbox |
β Summary
| Feature | Function |
|---|---|
| π¬ Basic Email | Send plain text messages |
| π HTML Email | Send rich formatted emails |
| π Attachment | Attach files automatically |
| π₯ Bulk Email | Send personalized messages from CSV |
| βοΈ Automation | Can run daily with cron/task scheduler |

Leave a Reply