Ask Your Question
3

How can I use Python to retrieve the most recently modified file within a folder and send it as an email attachment to a specified email address?

asked 2021-12-05 11:00:00 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-04-14 17:00:00 +0000

lakamha gravatar image

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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2021-12-05 11:00:00 +0000

Seen: 21 times

Last updated: Apr 14 '21