Automating Email Attachments: Finding the Latest Timestamped File in Python
Sending emails with attached files is a common task, but it often involves manually selecting the right file. This process can be tedious, especially if you're dealing with frequently updated files. This article will show you how to automate this process in Python by finding the latest file based on its timestamp and attaching it to an email.
The Problem
Imagine you have a folder containing multiple files with timestamps in their names, like "report_20231027.pdf" and "report_20231028.pdf." You want to automatically attach the most recent file to an email. How do you identify the latest file based on its timestamp?
The Solution: Using Python
import os
import email
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
def find_latest_file(directory, file_pattern):
"""
Finds the latest file in a directory matching a given pattern.
Args:
directory (str): The directory to search in.
file_pattern (str): The pattern to match file names (e.g., "report_*.pdf").
Returns:
str: The path to the latest file, or None if no matching file is found.
"""
latest_file = None
latest_timestamp = 0
for filename in os.listdir(directory):
if filename.startswith(file_pattern):
timestamp = int(filename.split("_")[1].split(".")[0])
if timestamp > latest_timestamp:
latest_timestamp = timestamp
latest_file = os.path.join(directory, filename)
return latest_file
def send_email(sender_email, sender_password, recipient_email, subject, body, attachment_path):
"""
Sends an email with an attachment.
Args:
sender_email (str): The sender's email address.
sender_password (str): The sender's email password.
recipient_email (str): The recipient's email address.
subject (str): The email subject.
body (str): The email body.
attachment_path (str): The path to the attachment file.
"""
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = recipient_email
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
if attachment_path:
with open(attachment_path, 'rb') as f:
part = MIMEBase('application', 'octet-stream')
part.set_payload(f.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(attachment_path))
msg.attach(part)
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
server.login(sender_email, sender_password)
server.sendmail(sender_email, recipient_email, msg.as_string())
# Example usage
directory = "/path/to/your/files"
file_pattern = "report_*"
attachment_path = find_latest_file(directory, file_pattern)
sender_email = "[email protected]"
sender_password = "your_password"
recipient_email = "[email protected]"
subject = "Latest Report"
body = "Please find the latest report attached."
send_email(sender_email, sender_password, recipient_email, subject, body, attachment_path)
print("Email sent successfully!")
Explanation
-
find_latest_file(directory, file_pattern)
Function:- Takes the directory path and a file pattern as input.
- Iterates through all files in the directory.
- Extracts the timestamp from the filename using string manipulation.
- Keeps track of the latest timestamp and corresponding file path.
- Returns the path to the latest file or
None
if no matching files are found.
-
send_email(sender_email, sender_password, recipient_email, subject, body, attachment_path)
Function:- Takes sender's email, password, recipient's email, subject, body, and attachment path as input.
- Creates a multipart email message using
MIMEMultipart
. - Adds the subject, body, and attachment to the message.
- Uses
smtplib
to connect to the Gmail SMTP server and send the email.
-
Example Usage:
- Defines the directory containing the files and the file pattern.
- Calls
find_latest_file
to get the path to the latest file. - Sets sender's email, password, recipient's email, subject, and body.
- Calls
send_email
to send the email with the attachment.
Additional Tips
- Error Handling: Consider adding error handling to the code to gracefully handle situations like missing files or invalid email credentials.
- Security: Store your email password securely. Consider using environment variables or a dedicated password manager.
- Customization: Adapt the code to your specific needs. Change the file pattern, email settings, and message content according to your requirements.
Conclusion
This Python script provides a simple and efficient solution for automatically attaching the latest timestamped file to an email. By automating this process, you can save time and improve workflow efficiency. Remember to adapt the code to your specific use case and prioritize security when handling sensitive information like email credentials.