如何自动过滤电子邮件附件中的最新文件 Python
How to automaticlly filter most recent file in email attachments Python
我有一些代码可以使用 MIME 模块从电子邮件附加文件
但是每次我发送电子邮件时,我都希望它自动发送
文件中只有前 5 张最近的图片。
import os, re
import sys
import smtplib
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = 587
sender = '***@gmail.com'
password = "*******"
recipient = '***@gmail.com'
subject = 'Python emaillib Test'
message = 'Images attached.'
directory = "images/"
def main():
msg = MIMEMultipart()
msg['Subject'] = 'Python emaillib Test'
msg['To'] = recipient
msg['From'] = sender
#this is where it searches for the image
files = os.listdir(directory)
jpgsearch = re.compile(".jpg", re.IGNORECASE)
files = filter(jpgsearch.search, files)
for filename in files:
path = os.path.join(directory, filename)
if not os.path.isfile(path):
continue
img = MIMEImage(open(path, 'rb').read(), _subtype="jpg")
img.add_header('Content-Disposition', 'attachment', filename = filename)
msg.attach(img)
part = MIMEText('text', "plain")
part.set_payload(message)
msg.attach(part)
session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
session.ehlo()
session.starttls()
session.ehlo
session.login(sender, password)
session.sendmail(sender, recipient, msg.as_string())
session.quit()
if __name__ == '__main__':
main()
我是 Python 的初学者,希望能提供帮助
使用os.stat获取atime、ctime或mtime。然后简单比较时间戳(或者使用一些其他基于datetime.datetime.fromtimestamp的逻辑)
我有一些代码可以使用 MIME 模块从电子邮件附加文件 但是每次我发送电子邮件时,我都希望它自动发送 文件中只有前 5 张最近的图片。
import os, re
import sys
import smtplib
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = 587
sender = '***@gmail.com'
password = "*******"
recipient = '***@gmail.com'
subject = 'Python emaillib Test'
message = 'Images attached.'
directory = "images/"
def main():
msg = MIMEMultipart()
msg['Subject'] = 'Python emaillib Test'
msg['To'] = recipient
msg['From'] = sender
#this is where it searches for the image
files = os.listdir(directory)
jpgsearch = re.compile(".jpg", re.IGNORECASE)
files = filter(jpgsearch.search, files)
for filename in files:
path = os.path.join(directory, filename)
if not os.path.isfile(path):
continue
img = MIMEImage(open(path, 'rb').read(), _subtype="jpg")
img.add_header('Content-Disposition', 'attachment', filename = filename)
msg.attach(img)
part = MIMEText('text', "plain")
part.set_payload(message)
msg.attach(part)
session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
session.ehlo()
session.starttls()
session.ehlo
session.login(sender, password)
session.sendmail(sender, recipient, msg.as_string())
session.quit()
if __name__ == '__main__':
main()
我是 Python 的初学者,希望能提供帮助
使用os.stat获取atime、ctime或mtime。然后简单比较时间戳(或者使用一些其他基于datetime.datetime.fromtimestamp的逻辑)