How to Write a Script to Automate Sending Daily Email Reports in Python
Table of Contents
- Introduction
- Prerequisites
- Overview of Email Automation
- Setting Up the Environment
- Installing Required Libraries
- Understanding the Email Protocol: SMTP
- Writing the Python Script
- Step 1: Importing Libraries
- Step 2: Defining Email Credentials
- Step 3: Creating the Email Content
- Step 4: Connecting to the SMTP Server
- Step 5: Sending the Email
- Step 6: Automating the Script with Scheduling
- Customizing the Email Report
- Attaching Files (e.g., CSV, PDF)
- Formatting Email Body with HTML
- Adding Error Handling
- Securing Credentials
- Automating with Task Schedulers
- Using Cron (Linux/macOS)
- Using Task Scheduler (Windows)
- Testing and Debugging the Script
- Conclusion
1. Introduction
Automation is a key component of modern workflows, and sending daily reports via email is one of the most common tasks that can be automated. Whether you’re sending performance summaries, sales data, or status updates, manually compiling and sending these reports can be time-consuming. Fortunately, Python makes it easy to automate this process.
This guide will walk you through how to write a Python script that automatically sends daily email reports. We will cover everything from setting up the environment to adding error handling and scheduling the task to run automatically every day.
2. Prerequisites
Before diving into the code, you should have the following:
- Basic knowledge of Python
- A valid email account (preferably Gmail, as we will be using Gmail’s SMTP server)
- A local Python environment set up on your machine
3. Overview of Email Automation
The goal of this blog is to create a Python script that:
- Connects to an email server (SMTP)
- Sends an email with a report
- Schedules the email to be sent daily
The basic process involves using the Python smtplib
library to connect to an SMTP server and send emails. You will also learn how to automate this task using scheduling tools like Cron (Linux/macOS) or Task Scheduler (Windows).
4. Setting Up the Environment
Installing Required Libraries
To send emails with Python, you need to install a few packages. While smtplib
is part of the Python standard library, other libraries can be useful for enhancing your script.
- smtplib: For sending the email.
- email.mime: For crafting the email content (text and attachments).
You can install any additional required packages using pip
. First, open your terminal or command prompt and run:
pip install schedule # For task scheduling (optional)
5. Understanding the Email Protocol: SMTP
Simple Mail Transfer Protocol (SMTP) is the protocol that mail servers use to send and receive emails. In this guide, we’ll use Gmail’s SMTP server to send the email, but you can adjust the settings for any other email provider that supports SMTP.
- Gmail SMTP Server:
smtp.gmail.com
- SMTP Port: 587 (TLS), 465 (SSL)
To use Gmail’s SMTP server, you will need to allow less secure apps to send emails from your account (or create an app-specific password if you have two-factor authentication enabled).
6. Writing the Python Script
Step 1: Importing Libraries
In the script, we need to import smtplib
to connect to the SMTP server, ssl
for a secure connection, and email.mime
to compose the email content.
import smtplib
import ssl
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import schedule
import time
Step 2: Defining Email Credentials
You’ll need to define the credentials for your email account. For security reasons, it’s recommended to use environment variables or store credentials in a separate configuration file.
sender_email = "your_email@gmail.com"
receiver_email = "receiver_email@gmail.com"
password = "your_email_password"
Step 3: Creating the Email Content
You can create both plain text and HTML content. HTML formatting allows you to create more visually appealing emails.
def create_email_content():
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = "Daily Report"
# Plain text part
body = "Hi,\nPlease find attached the daily report."
msg.attach(MIMEText(body, 'plain'))
# Attachments (optional, covered in a later section)
return msg
Step 4: Connecting to the SMTP Server
You’ll connect to the SMTP server using a secure connection.
def send_email():
msg = create_email_content()
context = ssl.create_default_context()
with smtplib.SMTP("smtp.gmail.com", 587) as server:
server.starttls(context=context) # Secure the connection
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, msg.as_string())
print("Email sent successfully!")
Step 5: Sending the Email
Now that the email content is created and the connection is established, you can send the email by calling the send_email()
function.
send_email()
Step 6: Automating the Script with Scheduling
To automate the sending of the email, we will use the schedule
library. You can define the time when you want the email to be sent daily.
def job():
send_email()
# Schedule the job every day at 9:00 AM
schedule.every().day.at("09:00").do(job)
while True:
schedule.run_pending()
time.sleep(1)
7. Customizing the Email Report
Attaching Files (e.g., CSV, PDF)
You may need to attach files to your email, such as daily reports in PDF or CSV format.
def attach_file(msg, file_path):
attachment = MIMEBase('application', 'octet-stream')
with open(file_path, 'rb') as file:
attachment.set_payload(file.read())
encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition', f'attachment; filename={file_path}')
msg.attach(attachment)
# Example usage
attach_file(msg, 'report.pdf')
Formatting Email Body with HTML
If you want to create a more visually appealing report, you can use HTML in your email body.
def create_html_email_content():
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = "Daily Report"
html_body = """
<html>
<body>
<h2>Daily Report</h2>
<p>Hi,</p>
<p>Please find attached the daily report.</p>
</body>
</html>
"""
msg.attach(MIMEText(html_body, 'html'))
return msg
8. Adding Error Handling
It’s important to add error handling in case there are issues with the connection or email credentials.
try:
send_email()
except Exception as e:
print(f"Failed to send email: {str(e)}")
9. Securing Credentials
Instead of hardcoding your email password into the script, consider using environment variables or a .env
file.
Environment Variables:
- Create environment variables for
EMAIL_USER
andEMAIL_PASS
. - In your Python script, use
os.getenv
to access them:
pythonimport os sender_email = os.getenv('EMAIL_USER') password = os.getenv('EMAIL_PASS')
- Create environment variables for
.env
File:- Store the credentials in a
.env
file and load them using thepython-dotenv
package.
- Store the credentials in a
10. Automating with Task Schedulers
Using Cron (Linux/macOS)
To schedule your script to run daily on Linux or macOS, you can use Cron.
- Open your terminal and type
crontab -e
to edit your Cron jobs. - Add the following line to run your Python script every day at 9 AM:
0 9 * * * /usr/bin/python3 /path/to/your/script.py
Using Task Scheduler (Windows)
On Windows, you can use Task Scheduler to automate the script:
- Open Task Scheduler and select “Create Basic Task”.
- Set the trigger to “Daily” and specify the time.
- In the “Action” tab, choose “Start a Program” and provide the path to the Python executable and your script.
11. Testing and Debugging the Script
It’s crucial to test the script thoroughly before putting it into production. Use the following tips to test and debug:
- Test Email Sending: Run the script manually to ensure that emails are sent correctly.
- Logging: Add logging to track when emails are sent and any errors that occur.
import logging
logging.basicConfig(filename='email_automation.log', level=logging.INFO)
logging.info("Email sent successfully!")
- Debugging SMTP Issues: If your emails aren’t being sent, check the logs and ensure your SMTP credentials are correct.
12. Conclusion
Automating daily email reports using Python is a practical and efficient way to streamline repetitive tasks. By following this guide, you’ve learned how to:
- Set up the environment for email automation
- Create a Python script that connects to an SMTP server and sends an email
- Customize the email with attachments and HTML formatting
- Schedule the script to run automatically every day
With the script in place, you can now automate the process of sending reports, saving time and reducing the risk of human error. This setup can easily be extended for other automation tasks, such as weekly or monthly reports, reminders, or notifications.
Happy coding!