Weekly Report Email Automation
PythonAutomationSummarizes a week of orders (revenue, change vs last week, refunds, top products) and writes a ready-to-review email file with the CSV attached. Sends nothing.
Run it
cd samples/weekly-report-email
python weekly_report.py 2026-10-12 # standard library onlyFiles: orders.csv · weekly_report.py
Generated summary
Week of 2026-10-12 to 2026-10-18
Orders: 35
Revenue: $2,085.47 (+5.7% vs previous week)
Refunds: 4
Top products:
- Tote bag: $603.97
- Hoodie: $602.90
- Notebook: $559.10
Download the .eml (HTML + plain text + CSV attachment)
Code
"""Builds a weekly summary email from an orders CSV and writes it to outbox/ as a .eml file (HTML + plain text,
CSV attached). It never sends anything; a person reviews the file, or a scheduler hands it to a mail service later.
Run: python weekly_report.py 2026-10-12 (standard library only; week starts Monday)"""
import csv, sys, datetime, os, html
from email.message import EmailMessage
start=datetime.date.fromisoformat(sys.argv[1] if len(sys.argv)>1 else "2026-10-12"); end=start+datetime.timedelta(days=6)
rows=[r for r in csv.DictReader(open("orders.csv")) if start<=datetime.date.fromisoformat(r["date"])<=end]
prev=[r for r in csv.DictReader(open("orders.csv")) if start-datetime.timedelta(7)<=datetime.date.fromisoformat(r["date"])<start]
rev=sum(float(r["total"]) for r in rows); prev_rev=sum(float(r["total"]) for r in prev)
by={}
for r in rows: by[r["product"]]=by.get(r["product"],0)+float(r["total"])
top=sorted(by.items(),key=lambda x:-x[1])[:3]
refunds=[r for r in rows if r["status"]=="refunded"]
chg=f"{(rev-prev_rev)/prev_rev*100:+.1f}%" if prev_rev else "n/a"
lines=[f"Week of {start} to {end}",f"Orders: {len(rows)}",f"Revenue: ${rev:,.2f} ({chg} vs previous week)",f"Refunds: {len(refunds)}","Top products:"]+[f" - {p}: ${v:,.2f}" for p,v in top]
msg=EmailMessage(); msg["Subject"]=f"Weekly sales summary: {start}"; msg["From"]="[email protected]"; msg["To"]="[email protected]"
msg.set_content("\n".join(lines)+"\n\n(Generated automatically from orders.csv. Draft for review; not sent.)")
msg.add_alternative("<h2>Weekly sales summary</h2><ul>"+"".join(f"<li>{html.escape(l.strip())}</li>" for l in lines)+"</ul>",subtype="html")
week_csv="date,order_id,product,total,status\n"+"".join(f"{r['date']},{r['order_id']},{r['product']},{r['total']},{r['status']}\n" for r in rows)
msg.add_attachment(week_csv.encode(),maintype="text",subtype="csv",filename=f"orders-{start}.csv")
os.makedirs("outbox",exist_ok=True); p=f"outbox/weekly-{start}.eml"; open(p,"wb").write(bytes(msg))
open("outbox/latest_summary.txt","w").write("\n".join(lines)+"\n")
print("\n".join(lines)); print("wrote",p)