Automating Daily Email Reports with Python

In the fast-paced world of business, staying on top of daily reports is crucial. Automating the process of sending these reports via email can save valuable time and ensure consistency. In this article, we’ll walk you through how to set up a Python script to send daily email reports automatically.


Why Automate Email Reports?

Automating email reports can significantly enhance productivity by:

  • Ensuring Timeliness: Reports are sent at the same time every day.
  • Reducing Manual Work: Eliminates the need to manually compile and send reports.
  • Increasing Accuracy: Reduces the risk of human error.

Prerequisites:

To follow this guide, you’ll need:

  • Basic knowledge of Python.
  • An email account (Gmail, Outlook, etc.) to send emails from.
  • A report file you want to send.

Setting Up the Environment:

First, you need to install the required Python packages. Open your terminal and run:

pip install schedule

This command installs the schedule package, which we’ll use to schedule the daily email task.


Writing the Python Script

Here’s a complete Python script to automate sending daily email reports:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import schedule
import time
import os

# Configuration
SMTP_SERVER = 'smtp.example.com'
SMTP_PORT = 587
SMTP_USERNAME = 'your_email@example.com'
SMTP_PASSWORD = 'your_password'
EMAIL_FROM = 'your_email@example.com'
EMAIL_TO = 'recipient@example.com'
EMAIL_SUBJECT = 'Daily Report'
REPORT_FILE = 'path_to_your_report_file.txt'

# Function to send email
def send_email():
    # Create the container email message
    msg = MIMEMultipart()
    msg['From'] = EMAIL_FROM
    msg['To'] = EMAIL_TO
    msg['Subject'] = EMAIL_SUBJECT

    # Attach the report file
    with open(REPORT_FILE, 'r') as file:
        report_content = file.read()

    msg.attach(MIMEText(report_content, 'plain'))

    # Send the email via SMTP server
    try:
        server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
        server.starttls()  # Upgrade to secure connection
        server.login(SMTP_USERNAME, SMTP_PASSWORD)
        server.sendmail(EMAIL_FROM, EMAIL_TO, msg.as_string())
        server.quit()
        print("Email sent successfully!")
    except Exception as e:
        print(f"Failed to send email: {e}")

# Schedule the email to be sent daily at a specific time (e.g., 08:00 AM)
def schedule_email():
    schedule.every().day.at("08:00").do(send_email)
    while True:
        schedule.run_pending()
        time.sleep(1)

if __name__ == "__main__":
    schedule_email()

Configuring Your Email Settings

To customize the script for your needs:

  • Replace SMTP_SERVER with your SMTP server address (e.g., smtp.gmail.com for Gmail).
  • Replace SMTP_PORT with the appropriate port (587 is commonly used for TLS).
  • Replace SMTP_USERNAME and SMTP_PASSWORD with your email account’s credentials.
  • Replace EMAIL_FROM with your email address.
  • Replace EMAIL_TO with the recipient’s email address.
  • Replace EMAIL_SUBJECT with the desired subject line for your email.
  • Replace REPORT_FILE with the path to your report file.

Running the Script

To start the script, simply execute it in your terminal:

python your_script_name.py

This script will continuously run and send the email every day at the specified time (08:00 AM in this example). You can adjust the time in the schedule.every().day.at("08:00").do(send_email) line to fit your needs.


Security Considerations

Storing plain text credentials in the script is not secure. Here are some alternatives:

  • Environment Variables: Store sensitive data in environment variables.
  • Configuration Files: Use configuration files that are not included in version control.
  • Secret Management Services: Utilize services like AWS Secrets Manager or Azure Key Vault.

Enhancing the Script

For a more robust solution, consider adding:

  • Error Logging: Log errors to a file for later review.
  • Email Attachments: Attach reports as files instead of plain text.
  • HTML Emails: Send emails with HTML content for better formatting.

Conclusion

Automating daily email reports with Python can save time, reduce errors, and ensure reports are sent consistently. With a few lines of code, you can set up a system that handles this task efficiently, allowing you to focus on more critical aspects of your work.

By following the steps outlined in this guide, you’ll be well on your way to streamlining your reporting process and enhancing productivity.

Leave a comment