Published 3 September 2024 /

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

Eddie Lewis

By Eddie Lewis

Automating repetitive tasks in today’s fast-paced digital world can save you valuable time and ensure consistency. One such task is sending daily email reports. Whether you’re sending updates to your team, reminding yourself of key metrics, or keeping clients informed, automation can make this task effortless. In this guide, we’ll walk you through setting up a Python script to automate your daily email reports.

Why Automate Email Reports?

Automation isn’t just about convenience; it’s about ensuring reliability and precision. Imagine never forgetting to send a daily update again. Your reports are sent at the same time, every day, with the same accuracy. This consistency can build trust with your recipients and free you up to focus on more important tasks.

Step 1: Install Required Libraries

Before we start, you need to have Python installed on your system. You’ll also need the `smtplib` and `email` libraries, which come with Python’s standard library, and the `schedule` library. Open your terminal and run:

```bash

pip install schedule

```

This command installs the `schedule` library, which we’ll use to automate the email sending process.

Step 2: Setting Up Your Python Script

First, let’s import the necessary libraries:

```python

import smtplib

from email.mime.multipart import MIMEMultipart

from email.mime.text import MIMEText

import schedule

import time

import os

```

Step 3: Define Email Parameters

You need to specify the details of your email, such as the sender and recipient addresses, the subject, and the body of the email. Here’s a function that sets up these parameters and sends the email:

```python

def send_email():

from_addr = '[email protected]'

to_addr = '[email protected]'

subject = 'Daily Report'

body = 'This is the daily report.'

msg = MIMEMultipart()

msg['From'] = from_addr

msg['To'] = to_addr

msg['Subject'] = subject

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

smtp_server = 'smtp.example.com'

smtp_port = 587

login = '[email protected]'

password = 'your_password'

try:

server = smtplib.SMTP(smtp_server, smtp_port)

server.starttls()

server.login(login, password)

server.sendmail(from_addr, to_addr, msg.as_string())

print('Email sent successfully')

except Exception as e:

print(f'Failed to send email: {e}')

finally:

server.quit()

```

Step 4: Automate the Sending Process

Now, let’s automate the email sending process. We’ll use the `schedule` library to run the `send_email` function at a specific time every day. Here’s how:

```python

def job():

send_email()

schedule.every().day.at("08:00").do(job)

while True:

schedule.run_pending()

time.sleep(1)

```

This snippet schedules the email to be sent every day at 8:00 AM. The `while True` loop keeps the script running, checking every second if it’s time to send the email.

Step 5: Secure Your Credentials

Hardcoding your email credentials in the script is not secure. Instead, use environment variables to store your email and password. Here’s how you can modify the `send_email` function to use environment variables:


def send_email():

from_addr = os.getenv('EMAIL_ADDRESS')

to_addr = '[email protected]'

subject = 'Daily Report'

body = 'This is the daily report.'

msg = MIMEMultipart()

msg['From'] = from_addr

msg['To'] = to_addr

msg['Subject'] = subject

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

smtp_server = 'smtp.example.com'

smtp_port = 587

login = from_addr

password = os.getenv('EMAIL_PASSWORD')

try:

server = smtplib.SMTP(smtp_server, smtp_port)

server.starttls()

server.login(login, password)

server.sendmail(from_addr, to_addr, msg.as_string())

print('Email sent successfully')

except Exception as e:

print(f'Failed to send email: {e}')

finally:

server.quit()

Ensure you set your environment variables in your system or a `.env` file.

Final Touches

Your script is ready to go! Save it as `daily_email_report.py` and run it. To keep it running, consider using a process manager like `pm2` or a task scheduler like `cron`.

Enhancing Your Script

1. **Logging**: Implement logging to monitor email sending status and errors.

2. **Attachments**: Use the `MIMEBase` module to attach files.

3. **Error Handling**: Enhance error handling to manage SMTP server or network issues effectively.

Conclusion

By following these steps, you’ve automated your daily email reports, saving you time and ensuring consistency. This small automation can significantly enhance your productivity, allowing you to focus on tasks that matter more. Happy coding!