You can use the following Python code to retrieve the most recently modified file within a folder and send it as an email attachment:
import os
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE
from email import encoders
# Set the folder directory and email parameters
folder_path = 'path/to/folder'
email_from = 'example@example.com'
email_to = 'recipient@example.com'
email_subject = 'Latest File Attachment'
# Get the most recently modified file within the folder
latest_file = max(os.listdir(folder_path), key=os.path.getctime)
file_path = os.path.join(folder_path, latest_file)
# Set up the email message
msg = MIMEMultipart()
msg['From'] = email_from
msg['To'] = COMMASPACE.join([email_to])
msg['Subject'] = email_subject
# Attach the file to the email message
attachment = MIMEBase('application', 'octet-stream')
attachment.set_payload(open(file_path, 'rb').read())
encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition', 'attachment', filename=latest_file)
msg.attach(attachment)
# Send the email
smtp_server = 'smtp.gmail.com'
smtp_port = 587
smtp_username = 'your_username'
smtp_password = 'your_password'
smtp_tls = True
smtp_server = smtplib.SMTP(smtp_server, smtp_port)
if smtp_tls:
smtp_server.starttls()
smtp_server.login(smtp_username, smtp_password)
smtp_server.sendmail(email_from, email_to, msg.as_string())
smtp_server.quit()
Note: - Replace 'path/to/folder' with the directory path to your folder containing the files. - Replace 'example@example.com' and 'recipient@example.com' with your email address and the recipient's email address respectively. - Replace 'yourusername' and 'yourpassword' with your email login credentials.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2021-12-05 11:00:00 +0000
Seen: 21 times
Last updated: Apr 14 '21
How can I set up Gunicorn with a Django Project?
Looking for a Python Module that finds Tags for a Text describing its Content
Need a Function in Python to remove entries less than 2 digits from an Array
How can I convert a Document in Python?
How can I program a Loop in Python?
How can I enable Python Code Highlighting in Askbot?