DEV Community

Brad
Brad

Posted on

Automate Weekly Email Reports with Python: Send Business Digests

Automate Weekly Email Reports with Python

Stop manually compiling weekly reports. Python can gather data and email it automatically.

Build the Report Content

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

def get_weekly_stats():
    # Replace with your actual data sources
    return {
        "revenue": 12450,
        "new_signups": 87,
        "churn_rate": 2.1,
        "week": datetime.now().strftime("%Y-W%V")
    }

def format_report(stats):
    html = "<html><body>"
    html += "<h2>Weekly Report - " + stats['week'] + "</h2>"
    html += "<table border='1' cellpadding='8'>"
    html += "<tr><td>Revenue</td><td>$" + str(stats['revenue']) + "</td></tr>"
    html += "<tr><td>New Signups</td><td>" + str(stats['new_signups']) + "</td></tr>"
    html += "<tr><td>Churn Rate</td><td>" + str(stats['churn_rate']) + "%</td></tr>"
    html += "</table></body></html>"
    return html
Enter fullscreen mode Exit fullscreen mode

Send the Email

def send_report(recipients, subject, html_body):
    msg = MIMEMultipart("alternative")
    msg["Subject"] = subject
    msg["From"] = "reports@yourcompany.com"
    msg["To"] = ", ".join(recipients)
    msg.attach(MIMEText(html_body, "html"))

    with smtplib.SMTP("smtp.gmail.com", 587) as server:
        server.starttls()
        server.login("reports@yourcompany.com", "your-app-password")
        server.sendmail("reports@yourcompany.com", recipients, msg.as_string())

stats = get_weekly_stats()
send_report(
    recipients=["ceo@company.com"],
    subject="Weekly Report " + stats['week'],
    html_body=format_report(stats)
)
Enter fullscreen mode Exit fullscreen mode

Schedule It to Run Every Monday

import schedule
import time

def monday_report():
    stats = get_weekly_stats()
    send_report(["team@company.com"], "Weekly Digest", format_report(stats))

schedule.every().monday.at("08:00").do(monday_report)

while True:
    schedule.run_pending()
    time.sleep(60)
Enter fullscreen mode Exit fullscreen mode

Pull from Real APIs

import requests

def get_stripe_revenue(api_key, since_timestamp):
    headers = {"Authorization": "Bearer " + api_key}
    resp = requests.get(
        "https://api.stripe.com/v1/charges",
        headers=headers,
        params={"created[gte]": since_timestamp, "limit": 100}
    )
    charges = resp.json()["data"]
    return sum(c["amount"] for c in charges if c["paid"]) / 100
Enter fullscreen mode Exit fullscreen mode

Set this up once and you will never manually compile a weekly report again.


Want 50+ ready-to-use Python automation scripts? Get the complete toolkit for just $9: https://lukassbrad.gumroad.com/l/ugeka

Top comments (0)