Categories: Python
Tags:

Here’s a Python script to automate sending daily email reports using the smtplib and email libraries. I’ll also guide you through the setup process step by step.

Learn Python_ Automate Daily Email Reports


Python Script

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.utils import formatdate
from datetime import datetime
import schedule
import time

# Email configuration
SMTP_SERVER = 'smtp.gmail.com'  # For Gmail; replace with your provider's SMTP server if needed.
SMTP_PORT = 587
EMAIL_ADDRESS = 'your_email@gmail.com'
EMAIL_PASSWORD = 'your_email_password'
RECIPIENTS = ['recipient1@example.com', 'recipient2@example.com']  # List of recipients
SUBJECT = "Daily Report"

def create_email():
    """Creates the email content."""
    # Compose the email
    msg = MIMEMultipart()
    msg['From'] = EMAIL_ADDRESS
    msg['To'] = ', '.join(RECIPIENTS)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = SUBJECT

    # Body of the email
    body = f"Hello,\n\nThis is your daily report for {datetime.now().strftime('%Y-%m-%d')}.\n\nBest regards,\nAutomated Email Bot"
    msg.attach(MIMEText(body, 'plain'))

    # Example attachment (optional)
    try:
        with open("daily_report.pdf", "rb") as attachment:  # Replace with your file path
            part = MIMEApplication(attachment.read(), Name="daily_report.pdf")
            part['Content-Disposition'] = 'attachment; filename="daily_report.pdf"'
            msg.attach(part)
    except FileNotFoundError:
        print("Attachment not found, sending without it.")

    return msg

def send_email():
    """Sends the email."""
    try:
        msg = create_email()
        with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
            server.starttls()
            server.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
            server.sendmail(EMAIL_ADDRESS, RECIPIENTS, msg.as_string())
        print(f"Email sent successfully at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    except Exception as e:
        print(f"Failed to send email: {e}")

# Schedule the task daily at a specific time (e.g., 8:00 AM)
schedule.every().day.at("08:00").do(send_email)

if __name__ == "__main__":
    print("Email automation started. Waiting for the scheduled time...")
    while True:
        schedule.run_pending()
        time.sleep(1)

Setup Steps

  1. Set Up Your Email Account
    • Gmail: Enable Allow less secure apps or set up an App Password if you have two-factor authentication enabled.
    • Other Providers: Ensure SMTP access is enabled. Check your provider’s documentation for settings.
  2. Install Required Libraries Ensure you have Python installed, then install the necessary library: pip install schedule
  3. Modify the Script
    • Replace your_email@gmail.com and your_email_password with your email address and password or app password.
    • Update the RECIPIENTS list with the recipient email addresses.
    • Adjust the scheduled time ("08:00") as needed.
  4. Run the Script
    • Save the script as daily_email_report.py.
    • Run it using Python: python daily_email_report.py
    • Keep the script running to ensure emails are sent daily.
  5. Automate Script Execution (Optional)
    • On Windows: Use Task Scheduler to run the script daily.
    • On macOS/Linux: Add a cron job (e.g., 0 8 * * * python3 /path/to/daily_email_report.py).
  6. Testing
    • Before scheduling, test the script by temporarily replacing schedule.every().day.at("08:00").do(send_email) with: send_email()
    • Run the script to ensure emails are sent successfully.

With this setup, your daily email reports will be sent automatically! Let me know if you need help with any part of this process.