Email & Notification Automation
Learn to automate email sending and notifications with Python — scheduled reports, conditional alerts, HTML emails, and integration with messaging platforms.
🔄 Recall Bridge: In the previous lesson, you integrated with REST APIs — fetching data, handling pagination, and building data pipelines. Now let’s add the communication layer: sending emails and notifications from your automation scripts.
Email and notifications turn your automation scripts from tools you run manually into systems that communicate results, send alerts, and deliver reports on schedule.
Sending Email with Python
Python’s smtplib handles SMTP (email sending). For modern accounts, you’ll typically need an app-specific password (not your regular password).
Setting up Gmail app passwords:
- Enable 2-Factor Authentication on your Google account
- Go to Google Account → Security → App passwords
- Generate a password for “Mail” on “Other”
- Store this password in your
.envfile
Script 1: Basic Email Sender
AI prompt:
Write a Python script that sends an email using smtplib: (1) Read SMTP credentials from environment variables (SMTP_SERVER, SMTP_PORT, EMAIL_USER, EMAIL_PASSWORD), (2) Support both plain text and HTML body, (3) Support file attachments (CSV, Excel, PDF), (4) Accept recipients, subject, and body as function parameters, (5) Include proper error handling for connection failures, authentication errors, and send failures. Create a reusable send_email() function I can import from other scripts.
Core email-sending pattern:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# 1. Create message
msg = MIMEMultipart("alternative")
msg["Subject"] = "Daily Report"
msg["From"] = sender
msg["To"] = ", ".join(recipients)
# 2. Attach both plain text and HTML
msg.attach(MIMEText(plain_text, "plain"))
msg.attach(MIMEText(html_content, "html"))
# 3. Send
with smtplib.SMTP(smtp_server, port) as server:
server.starttls()
server.login(username, password)
server.send_message(msg)
Script 2: HTML Report Email
AI prompt:
Write a Python function that generates an HTML email report from a pandas DataFrame: (1) Convert the DataFrame to an HTML table with inline CSS: alternating row colors, bold headers, right-aligned numbers, (2) Add a summary section above the table: total rows, key metrics (sum, average of numeric columns), (3) Include the report date and a brief header, (4) Provide a plain text alternative that formats the same data as an aligned text table, (5) Attach the raw data as a CSV file. I want to call this function from my data processing scripts to email results automatically.
Script 3: Conditional Alerts
AI prompt:
Write a Python alert system that monitors conditions and sends notifications: (1) Accept a list of conditions to check (e.g., “price below $50”, “stock out of inventory”, “API response time > 5 seconds”), (2) For each triggered condition, send an email alert with details, (3) Throttle alerts: max 1 alert per condition per hour (track in a local JSON file), (4) Global cap: max 10 alerts per hour total, (5) Log all alerts (sent and suppressed) to a CSV file, (6) Support urgency levels: “info” (email only), “warning” (email + console), “critical” (email + console + repeat after 15 min). Return a summary of alerts sent and suppressed.
Alternative Notification Channels
Email isn’t the only option. Many automation scripts benefit from instant messaging:
| Channel | Library | Best For |
|---|---|---|
| Slack | slack_sdk | Team notifications, channel alerts |
| Discord | discord-webhook | Personal alerts, community bots |
| Telegram | python-telegram-bot | Mobile-friendly personal alerts |
| Desktop | plyer | Local popup notifications |
AI prompt for Slack notifications:
Write a Python function that sends a notification to a Slack channel using a webhook URL: (1) Accept message text, optional title, and urgency level (info/warning/critical), (2) Format using Slack Block Kit for rich formatting, (3) Include color coding: green for info, yellow for warning, red for critical, (4) Read the webhook URL from environment variables.
Notification Best Practices
| Practice | Why | Implementation |
|---|---|---|
| Throttle alerts | Prevent alert storms | Cooldown per condition + global cap |
| Include context | Recipients need actionable info | What triggered, current value, threshold, link to details |
| Plain text fallback | Not all clients render HTML | MIME multipart with both formats |
| Test with yourself first | Catch formatting issues before team sees them | Send to your own email before adding recipients |
| Unsubscribe mechanism | Respect recipients | Configuration file for notification preferences |
✅ Quick Check: Your script sends daily emails at 8 AM. You want to skip weekends. Where should this logic live — in the email script or in the scheduler? (Answer: In the scheduler, not the email script. The email script’s job is to compose and send emails when called. The scheduler’s job is to decide when to call the email script. Separating these concerns means you can reuse the email script for other schedules — like weekly summaries on Friday or ad-hoc alerts any time. AI prompt: “Add a schedule configuration to my automation: run daily at 8 AM on weekdays only, with a separate schedule for a weekly summary on Fridays at 5 PM.”)
Key Takeaways
- Never hardcode email credentials — use environment variables or app-specific passwords that can be revoked independently; transactional email services (SendGrid, Mailgun) with send-only API keys are even more secure than SMTP with your personal email password
- Build alert throttling from the start: cooldown periods per condition, global alert caps, and de-duplication prevent one error from flooding your inbox with hundreds of notifications — this protects you from bugs you haven’t written yet
- HTML emails with simple inline-CSS tables make automated reports immediately readable without opening attachments — always include a plain text fallback since some email clients strip HTML
Up Next
In the next lesson, you’ll learn scheduling and error handling — running your scripts automatically on a schedule and making them reliable enough to run unattended.
Knowledge Check
Complete the quiz above first
Lesson completed!