How to Automate Daily Email Reports with Python: A Step-by-Step Guide

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

  1. Set Up Your Environment:

    • Make sure you have Python installed.

    • Install necessary libraries using pip. You will need smtplib for sending emails and email for email composition. Optionally, you can use dotenv to manage environment variables securely.

    pip install python-dotenv
  1. Create Environment Variables:

    • Create a .env file to store your email credentials and other configurations securely.
    EMAIL_HOST=smtp.gmail.com
    EMAIL_PORT=587
    EMAIL_ADDRESS=your-email@gmail.com
    EMAIL_PASSWORD=your-email-password
  1. 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)
    
  2. 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:

  1. Open Task Scheduler.

  2. Create a new basic task.

  3. Set the trigger to daily.

  4. Set the action to start a program and select your Python script.

Cron Job (macOS/Linux):

  1. Open your crontab file by running crontab -e in the terminal.

  2. 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

  1. Environment Setup:

    • The script begins by loading the environment variables for email configuration.

    • It uses dotenv to securely handle sensitive information like email credentials.

  2. 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.

  3. 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.

  4. 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.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!