Introduction
In this lesson, we will delve into using Python for automating the generation and sending of reports and notifications. We'll explore how to configure SMTP settings securely, generate dynamic PDFs, and automate the emailing process with attachments. Additionally, we'll touch on scheduling with cron and Task Scheduler to ensure tasks run periodically, and how to handle errors and logging effectively.
Configuring SMTP for Automated Emails
To send emails automatically via Python, we use the smtplib library and configure secure SMTP settings. It's crucial to handle authentication securely using environmental variables or secure stores.
import smtplib
from email.message import EmailMessage
EMAIL_ADDRESS = 'your-email@example.com'
EMAIL_PASSWORD = 'your-password'
msg = EmailMessage()
msg['Subject'] = 'Automated Report'
msg['From'] = EMAIL_ADDRESS
msg['To'] = 'recipient@example.com'
msg.set_content('Please find attached the latest report.')
with smtplib.SMTP_SSL('smtp.example.com', 465) as smtp:
smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
smtp.send_message(msg)
Generating Dynamic PDF Reports
To generate PDFs dynamically, we can use libraries such as ReportLab or FPDF. These libraries allow you to create documents dynamically based on data inputs.
from fpdf import FPDF
doc = FPDF()
doc.add_page()
doc.set_font("Arial", size=12)
doc.cell(200, 10, txt="Hello World", ln=True, align='C')
doc.output("test_report.pdf")
Attaching PDFs and Files to Emails
When sending reports via email, we often need to attach files. This can be done using the MIME protocol with the email library.
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
msg = MIMEMultipart()
msg.attach(EmailMessage())
with open('report.pdf', 'rb') as file:
attach = MIMEApplication(file.read(), Name='report.pdf')
attach['Content-Disposition'] = 'attachment; filename="report.pdf"'
msg.attach(attach)
Scheduling Tasks with Cron or Task Scheduler
To keep reports and emails automated, scheduling tasks is essential. On Unix-based systems, cron is used, while Windows offers Task Scheduler. Here is an example of a cron job entry to automate tasks daily:
0 6 * * * /usr/bin/python3 /path/to/script.py
This line would execute the script every day at 6 AM.
Handling Errors and Logging
In automation, logging is crucial for monitoring tasks and capturing errors. Using the logging module helps keep track of operations and track issues efficiently.
import logging
logging.basicConfig(filename="automation.log", level=logging.DEBUG)
try:
# Code for automation
pass
except Exception as err:
logging.error("Error occurred: %s", err)
Summary / Key Takeaways
In this lesson Automating Reports and Notifications (Email, PDFs), you have learned:
- Securely configure SMTP settings: Use Python to automate email sending securely with authentication.
- Generate dynamic PDFs: Utilize ReportLab or FPDF for creating flexible, data-driven PDF documents.
- Automate email attachments: Attach PDFs and additional files to emails with
email.mimelibraries. - Schedule tasks with cron/Task Scheduler: Ensure automation scripts run periodically and reliably.
- Implement robust error handling: Utilize Python's logging capabilities to monitor automated workflows and catch errors effectively.
