AW Dev Rethought

Code is read far more often than it is written - Guido van Rossum

🧩 Python Automation Recipes – 📧 Auto Email Reports


Description:

📌 Introduction

Generating reports is only half the job — delivering them automatically is what saves real time.

In many teams, reports still get generated manually and emailed by hand.

This automation recipe shows how to generate a simple report and email it automatically using Python.

It’s ideal for daily summaries, weekly metrics, system stats, or CSV/Excel reports.


🔎 Explanation

  • The script:
    • generates a basic text-based report (can be replaced with CSV/Excel later)
    • builds an email with subject and body
    • sends it using Python’s built-in smtplib
  • No external email services are required.
  • The script can easily be combined with:
    • the Scheduled Task Runner
    • CSV/Excel generators
    • system monitors

This is one of the most common real-world automation patterns.


✅ Key Takeaways

  • 📧 Automate report delivery via email.
  • ⏱️ Perfect for scheduled daily or weekly reports.
  • ⚙️ Uses standard Python libraries — simple and reliable.

Code Snippet:

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

# --- Step 1: Email configuration ---

SENDER_EMAIL = "your_email@gmail.com"        # Change this
SENDER_PASSWORD = "YOUR_APP_PASSWORD"        # Use app password
RECEIVER_EMAIL = "receiver@example.com"

SMTP_SERVER = "smtp.gmail.com"
SMTP_PORT = 587

# --- Step 2: Generate report content ---
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

report_content = f"""
Daily Automation Report
-----------------------
Generated at: {now}

• All systems operational
• No errors detected
• Report generated automatically by Python
"""

# --- Step 3: Create email ---
message = MIMEMultipart()
message["From"] = SENDER_EMAIL
message["To"] = RECEIVER_EMAIL
message["Subject"] = "Automated Daily Report"

message.attach(MIMEText(report_content, "plain"))

# --- Step 4: Send email ---
try:
    server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
    server.starttls()
    server.login(SENDER_EMAIL, SENDER_PASSWORD)
    server.send_message(message)
    server.quit()

    print("Report emailed successfully!")

except Exception as e:
    print("Failed to send email:", e)

Link copied!

Comments

Add Your Comment

Comment Added!