Certainly! To automate sending daily email reports in Python, you can use the smtplib library for sending emails and schedule for scheduling the task. Additionally, you may want to use the email library to compose and format the email. Here's a simple example script that sends a daily email report:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import schedule
import time
def send_email(subject, body, to_email, smtp_server, smtp_port, smtp_username, smtp_password):
# Set up the MIME
msg = MIMEMultipart()
msg['From'] = smtp_username
msg['To'] = to_email
msg['Subject'] = subject
# Attach the email body
msg.attach(MIMEText(body, 'plain'))
# Connect to the SMTP server and send the email
with smtplib.SMTP(smtp_server, smtp_port) as server:
server.starttls() # Use TLS for secure connection
server.login(smtp_username, smtp_password)
server.sendmail(smtp_username, to_email, msg.as_string())
def daily_report():
# Replace with your report generation logic
report_body = "Daily report content goes here."
# Set up email parameters
subject = "Daily Report"
to_email = "recipient@example.com"
smtp_server = "smtp.example.com"
smtp_port = 587
smtp_username = "your_email@example.com"
smtp_password = "your_email_password"
# Send the email
send_email(subject, report_body, to_email, smtp_server, smtp_port, smtp_username, smtp_password)
print("Daily report sent successfully!")
# Schedule the daily_report function to run every day at a specific time
schedule.every().day.at("08:00").do(daily_report)
# Keep the script running to execute scheduled tasks
while True:
schedule.run_pending()
time.sleep(1)
Now, let's walk through how to set it up:
1. Install Required Packages:
Make sure you have the required packages installed. You can install them using pip:
pip install schedule
2. Replace Placeholder Data:
Replace the placeholder data in the script with your actual email and SMTP server details.
3. Update Report Logic:
Modify the daily_report function to generate your actual daily report. This can include fetching data from a database, generating a CSV report, or any other relevant task.
4. Run the Script:
Save the script with a .py extension and run it using the command:
python your_script_name.py
The script will run indefinitely, checking for scheduled tasks and sending the daily report at the specified time.
Make sure to secure your email credentials and other sensitive information. You might consider using environment variables or a configuration file for this purpose. Additionally, if your email provider requires two-factor authentication, you might need to generate an "App Password" for the script.