Here’s how you can automate sending daily email reports in Python using smtplib
for sending emails and scheduling the job with the schedule
or APScheduler
library. I’ll walk you through the process step by step.
Step 1: Set Up Your Email Server Credentials
To send emails using Python, you’ll need access to an email SMTP server. For this example, let’s use Gmail’s SMTP server. First, create a .env
file or store your credentials securely for security reasons, especially if you’re sharing the code. Make sure to enable “Less secure apps” for your Gmail account or use OAuth for more security (Gmail is used here, but any email provider’s SMTP server can be used).
Step 2: Install Required Libraries
First, you need to install the required packages using pip
:
pip install schedule
pip install python-dotenv
Or, if you plan to use APScheduler for advanced scheduling:
pip install apscheduler
Step 3: Script to Send Email Reports
import smtplib
import schedule
import time
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from dotenv import load_dotenv
import os
# Load environment variables from a .env file
load_dotenv()
# Set up email credentials (or load them securely from environment variables)
EMAIL_ADDRESS = os.getenv('EMAIL_ADDRESS') # Your email address
EMAIL_PASSWORD = os.getenv('EMAIL_PASSWORD') # Your email password
TO_EMAIL = os.getenv('TO_EMAIL') # Recipient email address
# Email content generation function
def generate_email_report():
subject = "Daily Report"
body = """
Hello,
This is your daily report.
Best Regards,
Your Automation Script
"""
return subject, body
# Function to send email
def send_email(subject, body):
# Create the message
msg = MIMEMultipart()
msg['From'] = EMAIL_ADDRESS
msg['To'] = TO_EMAIL
msg['Subject'] = subject
# Attach the body of the email
msg.attach(MIMEText(body, 'plain'))
try:
# Set up the server and login
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls() # Secure the connection
server.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
# Send the email
server.sendmail(EMAIL_ADDRESS, TO_EMAIL, msg.as_string())
print(f"Email sent successfully to {TO_EMAIL}")
# Close the connection
server.quit()
except Exception as e:
print(f"Failed to send email. Error: {e}")
# Function to schedule and send the daily report
def daily_report_job():
subject, body = generate_email_report()
send_email(subject, body)
# Schedule the report to run daily at a specific time
schedule.every().day.at("09:00").do(daily_report_job) # Set to 9:00 AM
# Keep the script running
if __name__ == "__main__":
while True:
schedule.run_pending()
time.sleep(60) # Check every minute
Step 4: Environment Variables
Create a .env
file in the same directory with the following content:
[email protected]
EMAIL_PASSWORD=your_password
[email protected]
This .env
file will store sensitive data like your email credentials securely.
Step 5: How It Works
- Libraries:
smtplib
: Used to send the email via the SMTP protocol.schedule
: Used to run the function daily at a specified time.dotenv
: Loads email credentials from environment variables.email.mime.multipart
andemail.mime.text
: Helps structure the email and its content.
- Email Sending:
- The function
send_email
sets up an SMTP connection to Gmail, logs in, and sends an email to the recipient.
- The function
- Scheduling:
- The
schedule.every().day.at("09:00").do(daily_report_job)
ensures that the report is sent daily at 9:00 AM.
- The
- Environment Variables:
- Store sensitive data in a
.env
file to avoid hardcoding them into the script.
- Store sensitive data in a
Step 6: Running the Script
- Run the Python script from the terminal or deploy it to a server.
python daily_email_report.py
- The script will run in the background and send an email every day at the specified time.
Advanced Option: Use APScheduler (Optional)
If you want a more flexible or robust scheduling solution, you can use APScheduler instead of schedule
.
Here’s a basic example of how to modify the script:
from apscheduler.schedulers.blocking import BlockingScheduler
# Function to schedule and send the daily report
def daily_report_job():
subject, body = generate_email_report()
send_email(subject, body)
# Schedule with APScheduler
scheduler = BlockingScheduler()
scheduler.add_job(daily_report_job, 'cron', hour=9, minute=0) # Run at 9:00 AM every day
if __name__ == "__main__":
scheduler.start()
Step 7: Deploying the Script
To deploy this script for continuous running, you can:
- Run it on a server like a VPS or cloud service.
- Use Cron jobs (Linux/macOS) or Task Scheduler (Windows) to keep it running daily without user interaction.