[英]How to automaticlly filter most recent file in email attachments Python
I have got some code to attach files from an email using MIME module however each time I send the email I want it to automatically send only the first 5 most recent pictures in the file. 我有一些代码可以使用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()
I am a beginner to Python so help would be appreciated 我是Python的初学者,所以将不胜感激
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.