How to Automate Sending Daily Email Reports with Python

As a computer science student, you’re constantly learning new ways to automate tasks, streamline processes, and improve efficiency. One such task you might want to automate is sending daily reports via email. Whether you’re tracking project progress, sending reminders, or sharing updates with teammates, Python has got your back.

In this blog post, we’ll walk through creating a simple Python script that automatically sends daily email reports. Not only will this make your life easier, but it’s also a great project to practice real-world skills in Python and task automation.

Why Automate Daily Emails?

Automating daily emails has plenty of use cases:

  • Send daily updates: If you’re part of a team project, sending daily status reports can keep everyone in sync.
  • Project management: Automate progress tracking by sending reports at the end of each day.
  • Reminders: Keep your inbox clutter-free by scheduling important reminders or to-do lists automatically.

What You’ll Need

  • Basic knowledge of Python
  • A working Python environment
  • An email account (we’ll use Gmail in this example, but you can use any email provider)
  • Libraries like smtplibemail, and schedule

Let’s get started!

Step 1: Install the Required Libraries

The core libraries we’ll use are built-in, but we’ll also use the schedule library to handle the timing of our script.

First, install schedule by running this command:

pip install schedule

Step 2: Writing the Script to Send Emails

We’ll use Python’s smtplib to connect to an SMTP server and send the email, and the email library to format the message. Here’s the basic script:

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

# Email settings
SMTP_SERVER = 'smtp.gmail.com'  # Your SMTP server (Gmail example)
SMTP_PORT = 587
EMAIL = 'youremail@gmail.com'
PASSWORD = 'yourpassword'

def send_email():
    # Email content
    to_email = 'recipient@example.com'
    subject = 'Daily Report'
    body = 'Here is your daily report.'

    # Set up the email
    msg = MIMEMultipart()
    msg['From'] = EMAIL
    msg['To'] = to_email
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain'))

    # Optional: Attach a report (PDF, CSV, etc.)
    attachment_path = 'path/to/your/report.pdf'
    if os.path.exists(attachment_path):
        with open(attachment_path, 'rb') as attachment:
            part = MIMEBase('application', 'octet-stream')
            part.set_payload(attachment.read())
            encoders.encode_base64(part)
            part.add_header('Content-Disposition', f'attachment; filename={os.path.basename(attachment_path)}')
            msg.attach(part)

    # Send the email
    try:
        server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
        server.starttls()  # Secure the connection
        server.login(EMAIL, PASSWORD)
        server.sendmail(EMAIL, to_email, msg.as_string())
        print("Email sent successfully.")
    except Exception as e:
        print(f"Failed to send email: {e}")
    finally:
        server.quit()

# Schedule the email to be sent every day at 9:00 AM
schedule.every().day.at("09:00").do(send_email)

while True:
    schedule.run_pending()
    time.sleep(60)  # Check every minute

Step 3: Understanding the Code

Here’s what’s happening in the script:

  1. Setting Up SMTP: We connect to the email provider’s SMTP server. For Gmail, that’s smtp.gmail.com, and we use port 587. If you’re using a different provider like Yahoo or Outlook, you’d update those values accordingly.
  2. Creating the Email: We use MIMEMultipart() to create an email that can contain both text and attachments (like a daily report in PDF or CSV format). The email body is added with MIMEText(), and attachments are handled using MIMEBase.
  3. Sending the Email: Using smtplib.SMTP(), we connect to the SMTP server and send the email using our login credentials.
  4. Scheduling the Script: The schedule library allows us to send the email daily at a set time, which is 9:00 AM in this example.

Step 4: Setting Up Gmail to Work with Python

If you’re using Gmail, you’ll need to tweak your account settings:

  1. Allow less secure apps: If you don’t have two-factor authentication (2FA) enabled, go to your Google Account settings and enable “Less secure app access.” This will allow your Python script to connect.
  2. For 2FA Users: If you have 2FA enabled (which is recommended), you’ll need to create an App Password in your Google Account to use instead of your regular password.

Step 5: Running the Script Daily

To run the script every day without manually launching it, you can schedule it using a cron job (on Linux/Mac) or Task Scheduler (on Windows).

On Linux/Mac:

  1. Open your terminal and type:bashCopy codecrontab -e
  2. Add the following line to schedule the script:bashCopy code0 9 * * * /usr/bin/python3 /path/to/your/script.py This will run the script every day at 9:00 AM.

On Windows:

  1. Open Task Scheduler from the Start Menu.
  2. Create a new task, choose the trigger to run daily at your desired time, and select the action to start your Python script.

Step 6: Adding Error Handling and Logs

To make the script more reliable, you can add error handling and logging:

import logging

logging.basicConfig(filename='email_report.log', level=logging.INFO)

def send_email():
    try:
        # Same code as above
        logging.info("Email sent successfully.")
    except Exception as e:
        logging.error(f"Failed to send email: {e}")

Conclusion

And that’s it! You’ve just automated sending daily email reports with Python. This project is great practice for working with email servers, file handling, and scheduling. Plus, it’s an incredibly useful tool to automate those repetitive daily tasks.

As a computer science student, building automation scripts like this can significantly improve your efficiency, allowing you to focus on more challenging aspects of your studies or projects.

Happy coding!

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *