๐ Automating Email Reports with Python
Whether you're managing a project, analyzing sales, tracking prices, or scraping data — one thing’s for sure:
Emailing reports manually is a chore.
Let Python handle it for you!
In this post, you'll learn how to automate email reports that:
✅ Generate data or charts
✅ Save to PDF or Excel
✅ Send via email automatically
✅ Run daily, weekly, or on demand
๐งฐ Tools We’ll Use
-
pandas
— for creating the report -
matplotlib
orplotly
— for visualizations -
smtplib
— to send the email -
schedule
orcron
— to automate it -
email.message
— to handle formatting and attachments
Install required packages:
pip install pandas matplotlib schedule
๐งช Step 1: Create a Sample Report
import pandas as pd
import matplotlib.pyplot as plt
# Dummy sales data
data = {
'Date': pd.date_range(start='2025-04-01', periods=5),
'Sales': [200, 340, 560, 430, 620]
}
df = pd.DataFrame(data)
# Save to Excel
excel_path = "daily_report.xlsx"
df.to_excel(excel_path, index=False)
# Create a simple plot
plt.plot(df['Date'], df['Sales'], marker='o')
plt.title("Daily Sales Report")
plt.xlabel("Date")
plt.ylabel("Sales")
plt.tight_layout()
plt.savefig("sales_chart.png")
๐ฌ Step 2: Send the Report via Email
import smtplib
from email.message import EmailMessage
from pathlib import Path
EMAIL = "youremail@gmail.com"
APP_PASSWORD = "your_app_password"
msg = EmailMessage()
msg["Subject"] = "๐ Daily Sales Report"
msg["From"] = EMAIL
msg["To"] = "recipient@example.com"
msg.set_content("Attached is today's sales report and chart.")
# Attach Excel file
with open(excel_path, "rb") as f:
msg.add_attachment(f.read(), maintype="application", subtype="vnd.openxmlformats-officedocument.spreadsheetml.sheet", filename=Path(excel_path).name)
# Attach chart image
with open("sales_chart.png", "rb") as f:
msg.add_attachment(f.read(), maintype="image", subtype="png", filename="sales_chart.png")
# Send email
with smtplib.SMTP_SSL("smtp.gmail.com", 465) as smtp:
smtp.login(EMAIL, APP_PASSWORD)
smtp.send_message(msg)
print("✅ Report emailed successfully.")
๐ Step 3: Automate with schedule
import schedule
import time
def job():
print("๐
Generating and sending report...")
# Call your report generation + email code here
schedule.every().day.at("08:00").do(job)
while True:
schedule.run_pending()
time.sleep(60)
You can also run it via
cron
if you're on Linux/macOS for more reliability.
๐ Bonus: Add Dynamic Charts with Plotly
Want interactive HTML charts?
pip install plotly
import plotly.express as px
fig = px.line(df, x='Date', y='Sales', title='Sales Over Time')
fig.write_html("interactive_report.html")
Then attach or embed the HTML in your email.
✅ Use Cases
Scenario | Description |
---|---|
๐ข Team Updates | Send daily/weekly KPIs |
๐ Financial Reports | Email stock price summaries |
๐ฆ Inventory Tracking | Alert on low stock or trends |
๐ Error Logs | Email system logs and stats |
๐ Security Tips
-
Use App Passwords for Gmail
-
Never hardcode credentials — use
.env
files orkeyring
-
Set rate limits and logging to avoid spamming
๐ง Final Thoughts
Automating reports is a superpower. You can:
-
Save hours each week
-
Never forget to send a report
-
Keep clients/stakeholders up to date
-
Combine with scraping or analytics for full automation