Home
Atharv Gyan - how to Code
How to automate sending daily email reports in Python, and how I would set it up.
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:
Last updated