Categories Editorial Entertainment Exclusive

Write a script to automate sending daily email reports in Python, and walk me through how I would set it up.

Here’s a Python script to automate sending daily email reports. We’ll use the smtplib library for sending emails and schedule to run the task daily.


Script: Daily Email Automation

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

Function to send the email

def send_email():
# Email credentials and settings
sender_email = “your_email@example.com”
sender_password = “your_password”
receiver_email = “recipient@example.com”
subject = “Daily Report”

# Email content
body = "Hello,\n\nPlease find attached the daily report.\n\nBest regards,\nYour Automation Script"

# Create the email
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = subject

# Add email body
msg.attach(MIMEText(body, 'plain'))

# Attach a file (optional)
filename = "daily_report.pdf"  # Replace with your file name
try:
    with open(filename, '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={filename}',
    )
    msg.attach(part)
except FileNotFoundError:
    print("No attachment found. Skipping file attachment.")

# Send the email
try:
    with smtplib.SMTP('smtp.gmail.com', 587) as server:  # Use your SMTP server and port
        server.starttls()
        server.login(sender_email, sender_password)
        server.sendmail(sender_email, receiver_email, msg.as_string())
    print("Email sent successfully.")
except Exception as e:
    print(f"Failed to send email: {e}")

Schedule the task

schedule.every().day.at(“08:00”).do(send_email) # Adjust the time as needed

Run the scheduler

if name == “main“:
print(“Email scheduler is running…”)
while True:
schedule.run_pending()
time.sleep(60) # Check every minute


Setup Steps

  1. Install Required Libraries:

If schedule is not installed, install it using pip:

pip install schedule

  1. Configure SMTP Settings:

Update the sender_email, sender_password, and receiver_email with your email credentials.

Use the correct SMTP server and port for your email provider. For example:

Gmail: smtp.gmail.com, port 587

Outlook: smtp.office365.com, port 587

  1. Prepare the Attachment (Optional):

Place the file you want to attach (e.g., daily_report.pdf) in the same directory as the script. Update the filename variable if needed.

  1. Schedule the Script:

The script uses schedule to run the send_email function daily at the specified time. Update the time in the line:

schedule.every().day.at(“08:00”).do(send_email)

Ensure the script runs continuously, as shown in the while True loop.

  1. Run the Script:

Save the script as daily_email_report.py and run it:

python daily_email_report.py

  1. Enable Less Secure Apps:

For Gmail accounts, you might need to enable access for less secure apps or generate an app-specific password for enhanced security.

  1. Run as a Background Process (Optional):

Use a process manager like cron (Linux/Mac) or Task Scheduler (Windows) to run the script at startup or in the background.

Let me know if you need help customizing or troubleshooting the script!

Leave a Reply

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