π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 = "[email protected]"
receiver_email = "[email protected]"
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 = "[email protected]"
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:
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
Update Email Configuration: Replace
"[email protected]"
,"[email protected]"
, and"your_email_password"
with your actual email credentials. Ensure that you are using an email provider that allows SMTP access.Customize Email Content: Modify the
subject
andbody
variables in thesend_email
function to customize the content of your daily email report.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 inschedule.every().day.at()
.Run the Script: Save the script as, say,
daily_email_report.py
, and run it using Python:
python daily_email_report.py
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