Home

Atharv Gyan - how to Code

How to automate sending daily email reports in Python, and how I would set it up.

A basic script to automate sending daily email reports using Python, using the smtplib library for sending emails and schedule library for scheduling the task to run daily:

Python

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

def send_email():
    # Email content
    sender_email = "your_email@gmail.com"
    receiver_email = "recipient_email@example.com"
    subject = "Daily Report"
    body = "This is your daily report email."

    # Setup the MIME
    message = MIMEMultipart()
    message['From'] = sender_email
    message['To'] = receiver_email
    message['Subject'] = subject

    # Attach body to the email
    message.attach(MIMEText(body, 'plain'))

    # SMTP Server
    smtp_server = "smtp.gmail.com"
    smtp_port = 587
    smtp_username = "your_email@gmail.com"
    smtp_password = "your_email_password"

    # Login to the SMTP server
    server = smtplib.SMTP(smtp_server, smtp_port)
    server.starttls()
    server.login(smtp_username, smtp_password)

    # Send email
    server.sendmail(sender_email, receiver_email, message.as_string())
    print("Email sent successfully!")

    # Quit SMTP server
    server.quit()

# Schedule the email to be sent daily
schedule.every().day.at("08:00").do(send_email)

# Infinite loop to run the scheduler
while True:
    schedule.run_pending()
    time.sleep(60)  # Check every minute

How to set it up:

  1. Install Required Libraries: First, you need to install the schedule library if you haven't already. You can do this using pip:

pip install schedule
  1. Update Email Configuration: Replace "your_email@gmail.com", "recipient_email@example.com", and "your_email_password" with your actual email credentials. Ensure that you are using an email provider that allows SMTP access.

  2. Customize Email Content: Modify the subject and body variables in the send_email function to customize the content of your daily email report.

  3. Schedule Email Sending: The script is scheduled to send the email daily at 8:00 AM. You can adjust the time by modifying the "08:00" argument in schedule.every().day.at().

  4. Run the Script: Save the script as, say, daily_email_report.py, and run it using Python:

python daily_email_report.py
  1. Keep the Script Running: Since the script includes an infinite loop (while True), it will keep running indefinitely, checking every minute if there's any scheduled task to execute.

Once set up, the script will automatically send the daily email report at the specified time without any manual intervention.

Last updated