Here's a Python script to automate sending daily email reports. It uses the smtplib library to send emails via an SMTP server (e.g., Gmail) and can be scheduled using tools like cron on Linux or Task Scheduler on Windows.
Script to Send Daily Email Reports
Install Required Libraries
You will needsmtplib(comes with Python) andemail(also comes with Python) for sending the email. Optionally, you can usescheduleorAPSchedulerto set up daily scheduling within the script.If you want to schedule the script externally (e.g., with
cron), you don't need additional scheduling libraries. If you're on Windows, you can use Task Scheduler.Create the Email Report Script Save the following Python script:
pythonimport smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import os
import datetime
# Function to send email
def send_email(subject, body, attachment=None):
# Email configuration
sender_email = "your_email@gmail.com"
receiver_email = "receiver_email@example.com"
password = "your_password" # You can use environment variables for security
# Create the email container
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = subject
# Add body to email
msg.attach(MIMEText(body, 'plain'))
# Add an attachment if provided
if attachment:
attachment_name = os.path.basename(attachment)
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attachment, 'rb').read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', f'attachment; filename={attachment_name}')
msg.attach(part)
try:
# Establish a secure session with Gmail's outgoing SMTP server
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls() # Enable security
server.login(sender_email, password) # Login to the email account
text = msg.as_string()
server.sendmail(sender_email, receiver_email, text) # Send the email
server.quit() # Close the connection
print("Email sent successfully.")
except Exception as e:
print(f"Failed to send email: {e}")
# Function to generate the report (you can customize this)
def generate_report():
# You can generate the report content dynamically
today = datetime.datetime.now().strftime("%Y-%m-%d")
report_content = f"Daily Report for {today}\n\n"
report_content += "Here is the content of your daily report.\n"
return report_content
# Main function to send the daily report
if __name__ == "__main__":
subject = f"Daily Report - {datetime.datetime.now().strftime('%Y-%m-%d')}"
body = generate_report()
# If you have a file to attach (e.g., a PDF or CSV report), pass the file path here
attachment = None # Replace with 'path/to/report.pdf' if needed
# Send the email with the report
send_email(subject, body, attachment)
Explanation of the Script
Email Setup:
- You will need to provide your email address (
your_email@gmail.com) and password (your_password). If you use Gmail, you might need to enable Less Secure Apps or use an App Password from your Google account security settings. - You can change the SMTP server details (
smtp.gmail.com) if you're using a different email provider.
- You will need to provide your email address (
Report Generation:
- The
generate_report()function generates the content of the daily report. You can modify this function to pull data from a database, log file, or API. - The report content is included in the email body.
- The
Attachments:
- If you have a file (e.g., a PDF, CSV, or Excel report), you can attach it by providing the file path to the
attachmentvariable. If no attachment is needed, it will just send the email body.
- If you have a file (e.g., a PDF, CSV, or Excel report), you can attach it by providing the file path to the
Sending the Email:
- The
send_email()function handles the process of connecting to the SMTP server, logging in, and sending the email.
- The
How to Set Up and Schedule the Script
Step 1: Install the Required Libraries
No external libraries are required unless you're scheduling internally in Python. However, if you want the script to run daily within Python, you can install the schedule library by running:
bashpip install schedule
Step 2: Run the Script
You can run the script manually by running the following command:
bashpython daily_report.py
This will send the email immediately. Once you've tested it, you can schedule it to run automatically every day.
Step 3: Automate the Script
On Linux (using cron):
- Open the cron job editor:bash
crontab -e - Add the following line to schedule the script to run daily at 8:00 AM:
Replacebash0 8 * * * /usr/bin/python3 /path/to/your_script.py/path/to/your_script.pywith the actual path of the script.
On Windows (using Task Scheduler):
Open Task Scheduler and create a new task.
Set a daily trigger at your preferred time.
In the Actions tab, point to your Python executable and pass the path to your script as an argument.
Example:
- Program/script:
C:\Path\To\Python\python.exe - Add arguments:
C:\Path\To\Your\Script\daily_report.py
- Program/script:
Step 4: Use Environment Variables for Security (Optional)
For security reasons, it is recommended to avoid hardcoding your email password in the script. Instead, you can use environment variables.
Set environment variables:
- On Linux, add this to your
.bashrcor.bash_profile:bashexport EMAIL_USER="your_email@gmail.com" export EMAIL_PASSWORD="your_password" - On Windows, you can set them in the system environment variables.
- On Linux, add this to your
In the script, replace the hardcoded credentials with:
pythonimport os sender_email = os.getenv('EMAIL_USER') password = os.getenv('EMAIL_PASSWORD')
Conclusion
This setup should allow you to automatically send daily email reports. You can further customize the script by adding more dynamic report generation (e.g., reading from databases, adding charts, etc.). Scheduling it with cron or Windows Task Scheduler ensures it runs automatically at the desired time each day.

No comments:
Post a Comment
Note: Only a member of this blog may post a comment.