How to Automate Daily Email Reports with Python: A Step-by-Step Guide
I can help you create a Python script to automate sending daily email reports, and below is a step-by-step guide with a sample script to get you started.
Step-by-Step Guide
Set Up Your Environment:
Make sure you have Python installed.
Install necessary libraries using
pip
. You will needsmtplib
for sending emails andemail
for email composition. Optionally, you can usedotenv
to manage environment variables securely.
pip install python-dotenv
Create Environment Variables:
- Create a
.env
file to store your email credentials and other configurations securely.
- Create a
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_ADDRESS=your-email@gmail.com
EMAIL_PASSWORD=your-email-password
Write the Python Script:
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from datetime import datetime from dotenv import load_dotenv import os # Load environment variables from .env file load_dotenv() EMAIL_HOST = os.getenv('EMAIL_HOST') EMAIL_PORT = os.getenv('EMAIL_PORT') EMAIL_ADDRESS = os.getenv('EMAIL_ADDRESS') EMAIL_PASSWORD = os.getenv('EMAIL_PASSWORD') def send_email(subject, body, to_emails): # Create the email headers and body msg = MIMEMultipart() msg['From'] = EMAIL_ADDRESS msg['To'] = ', '.join(to_emails) msg['Subject'] = subject msg.attach(MIMEText(body, 'plain')) try: # Set up the server server = smtplib.SMTP(EMAIL_HOST, EMAIL_PORT) server.starttls() server.login(EMAIL_ADDRESS, EMAIL_PASSWORD) # Send the email server.sendmail(EMAIL_ADDRESS, to_emails, msg.as_string()) server.quit() print("Email sent successfully!") except Exception as e: print(f"Failed to send email: {e}") def generate_daily_report(): # Placeholder function to generate your report # You can replace this with your actual report generation logic report_date = datetime.now().strftime("%Y-%m-%d") report_body = f"Daily report for {report_date}\n\nAll systems operational." return report_body if __name__ == "__main__": # Email details subject = f"Daily Report - {datetime.now().strftime('%Y-%m-%d')}" body = generate_daily_report() to_emails = ['recipient1@example.com', 'recipient2@example.com'] # Send the email send_email(subject, body, to_emails)
Automate the Script:
Use a task scheduler to run your script daily.
For Windows, you can use Task Scheduler.
For macOS and Linux, you can use cron jobs.
Windows Task Scheduler:
Open Task Scheduler.
Create a new basic task.
Set the trigger to daily.
Set the action to start a program and select your Python script.
Cron Job (macOS/Linux):
Open your crontab file by running
crontab -e
in the terminal.Add the following line to run your script daily at a specified time (e.g., 8 AM):
0 8 * * * /usr/bin/python3 /path/to/your/script.py
Explanation
Environment Setup:
The script begins by loading the environment variables for email configuration.
It uses
dotenv
to securely handle sensitive information like email credentials.
Email Sending Function:
send_email
function composes the email and sends it using SMTP.It handles connecting to the email server, logging in, and sending the message.
Report Generation:
generate_daily_report
is a placeholder for generating your report content.Replace this with the logic needed to create your actual daily report.
Automation:
The main script composes the email details and sends it.
Scheduling ensures the script runs automatically each day at the specified time.
This setup provides a secure and automated way to send daily email reports using Python.