Automating email with smtplib and email
Email remains the lingua franca of alerts because every stakeholder already guards an inbox—but plain-text automation avoids HTML injection hazards when reporting pipeline status. smtplib negotiates SMTP transport while the email package composes MIME trees.
Never commit credentials—load from environment variables or secret managers touched in Working with APIs using requests.
📚 Prerequisites
- Understanding of MIME basics (sender, recipients, subject, body).
🎯 What you'll master
- Build
EmailMessageobjects with attachments when needed (optional preview). - Connect to SMTP with TLS (
starttls()).
Minimal notify script
import os
import smtplib
from email.message import EmailMessage
msg = EmailMessage()
msg["Subject"] = "[automation] nightly sync OK"
msg["From"] = os.environ["ALERT_FROM"]
msg["To"] = os.environ["ALERT_TO_LIST"]
msg.set_content(
"""Hello,
The ingestion job verified 412 files and exited 0.
"""
)
with smtplib.SMTP(os.environ["SMTP_HOST"], int(os.environ.get("SMTP_PORT", "587"))) as smtp:
smtp.starttls()
smtp.login(os.environ["SMTP_USER"], os.environ["SMTP_PASS"])
smtp.send_message(msg)
For Gmail-style providers prefer application-specific passwords or OAuth—not your primary password.
💡 Key takeaways
- Throttle bursts; providers rate-limit unidentified automation.
- Log SMTP reply codes distinctly from application logic failures.
➡️ Next steps
Manipulation of spreadsheets awaits in openpyxl.