Write a script to automate sending daily email reports in Python?
Sure, let’s walk through creating a Python script to automate sending daily email reports. The script will involve:
- Collecting or generating the report data.
- Formatting the report.
- Sending the email with the report attached or in the email body.
We’ll use the smtplib
library to send emails and email
library to create email content. For scheduling the script to run daily, we’ll use schedule
library.
Step 1: Set Up Your Environment
First, install necessary libraries if you don’t have them already:
pip install schedule
Step 2: Create the Script
Here’s a complete script to automate sending daily email reports:
import smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.mime.base import MIMEBasefrom email import encodersimport scheduleimport timedef generate_report(): # Replace this function with actual report generation logic return "This is a test report. Replace this with your actual report data."def send_email(report): # Email configuration sender_email = "[email protected]" receiver_email = "[email protected]" subject = "Daily Report" body = report smtp_server = "smtp.example.com" smtp_port = 587 login = "[email protected]" password = "your_email_password" # Create the email msg = MIMEMultipart() msg['From'] = sender_email msg['To'] = receiver_email msg['Subject'] = subject # Attach the body with the msg instance msg.attach(MIMEText(body, 'plain')) # Add any attachments if necessary (optional) # filename = "report.pdf" # attachment = open(filename, "rb") # 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) # Create SMTP session for sending the mail try: server = smtplib.SMTP(smtp_server, smtp_port) server.starttls() server.login(login, password) text = msg.as_string() server.sendmail(sender_email, receiver_email, text) server.quit() print("Email sent successfully") except Exception as e: print(f"Failed to send email: {e}")def job(): report = generate_report() send_email(report)# Schedule the job every day at 9:00 AMschedule.every().day.at("09:00").do(job)# Keep the script runningwhile True: schedule.run_pending() time.sleep(60)
Step 3: Configure Your Email
Replace placeholders in the script with your actual email details:
sender_email
: Your email address.receiver_email
: The recipient’s email address.smtp_server
: Your email provider’s SMTP server (e.g.,smtp.gmail.com
for Gmail).smtp_port
: SMTP server port (usually587
for TLS).login
: Your email address (usually the same assender_email
).password
: Your email account password or app-specific password.
Step 4: Generate the Report
Modify the generate_report
function to collect and format the actual report data. This could be from a database, file, or any other source you need.
Step 5: Scheduling the Script
The schedule
library will take care of running the job
function daily at the specified time (9:00 AM in the example). You can adjust the time as needed.
Step 6: Running the Script
To run the script, simply execute it:
python your_script.py
Ensure the script is running on a machine that stays on and connected to the internet. If you’re using a server or a cloud instance, make sure it doesn’t go to sleep or shut down.
Additional Tips
- Security: Use environment variables or a configuration file to store sensitive information like email passwords.
- Error Handling: Enhance error handling to manage potential failures more gracefully.
- Logging: Implement logging to keep track of the script’s execution status and troubleshoot issues.
This setup should help you automate sending daily email reports. If you have specific requirements or need further customization, feel free to ask!