Automate Sending Daily Email Reports in Python

Step-by-Step Guide

1. Install Necessary Libraries

Ensure you have Python installed. This script uses built-in libraries (smtplib and email), so no additional installations are required. For more complex tasks, you might need libraries like pandas for data manipulation or openpyxl for handling Excel files.

2. Set Up Email Configuration

  • Define your SMTP server details (e.g., for Gmail: smtp.gmail.com).
  • Set the sender’s and recipient’s email addresses.
  • Store your email account credentials securely.

3. Create the Email Content

  • Construct the subject and body of the email.
  • Optionally, attach files to the email.

4. Send the Email

  • Establish a connection to the SMTP server.
  • Log in using your credentials.
  • Send the email and handle any exceptions.

Sample Script

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

def send_email(subject, body, to_email, from_email, password, attachment_path=None):
    # Create a multipart message
    msg = MIMEMultipart()
    msg['From'] = from_email
    msg['To'] = to_email
    msg['Subject'] = subject

    # Attach the body with the msg instance
    msg.attach(MIMEText(body, 'plain'))

    # Attach any file if specified
    if attachment_path and 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)

    # Setup the SMTP server and send the email
    try:
        server = smtplib.SMTP('smtp.gmail.com', 587)  # Use your email provider's SMTP server and port
        server.starttls()
        server.login(from_email, password)
        text = msg.as_string()
        server.sendmail(from_email, to_email, text)
        print("Email sent successfully!")
    except Exception as e:
        print(f"Failed to send email: {e}")
    finally:
        server.quit()

if __name__ == "__main__":
    # Configuration
    from_email = "your_email@gmail.com"  # Replace with your email
    password = "your_password"  # Replace with your password (consider using environment variables for security)
    to_email = "recipient_email@example.com"  # Replace with recipient email

    # Email content
    subject = "Daily Report - " + datetime.now().strftime("%Y-%m-%d")
    body = "Hello,\n\nPlease find the daily report attached.\n\nBest regards,\nYour Name"
    attachment_path = "/path/to/report.xlsx"  # Replace with the path to your attachment if any

    # Send the email
    send_email(subject, body, to_email, from_email, password, attachment_path)

Detailed Setup Instructions

Configure Email and Password

  • Replace from_email and to_email with the actual email addresses.
  • Replace password with your email account’s password. For security reasons, consider using environment variables or a secure vault to store your password.

SMTP Server Details

  • The script uses Gmail’s SMTP server (smtp.gmail.com) and port (587). Adjust these settings if you’re using a different email provider.

Create Email Content

  • Modify the subject and body variables to customize the email content.
  • If you have an attachment, set attachment_path to the path of the file you want to attach.

Run the Script

  • Save the script as send_daily_report.py.
  • Run the script using python send_daily_report.py.

Scheduling the Script

To run this script daily, you can use a scheduling tool. For example:

  • Windows: Use Task Scheduler.
  • Mac/Linux: Use cron.

Example for cron

  1. Open the cron tab:
   crontab -e
  1. Add a new cron job (runs every day at 8 AM):
   0 8 * * * /usr/bin/python3 /path/to/your/send_daily_report.py

Make sure to replace /usr/bin/python3 with the path to your Python executable and /path/to/your/send_daily_report.py with the path to your script.

Conclusion

This guide provides a basic script to automate sending daily email reports using Python. Customize the script and schedule it as needed. If you have specific requirements or need further customization, feel free to ask!

Please follow and like us:

Leave a Reply

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