下载最近5天收到的附件(使用Python
问题描述
我还是个新手。这是我正在使用的工作代码,但我如何添加一个筛选器,以便只扫描和下载最近5天的电子邮件附件。
提前谢谢!
import os
from imbox import Imbox # pip install imbox
import traceback
import datetime
host = "imap.gmail.com"
username = "myemail@gmail.com"
password = '*******'
download_folder = "my/existing/dir"
if not os.path.isdir(download_folder):
os.makedirs(download_folder, exist_ok=True)
mail = Imbox(host, username=username, password=password, ssl=True, ssl_context=None, starttls=False)
# messages = mail.messages() # defaults to inbox
for (uid, message) in messages:
mail.mark_seen(uid) # optional, mark message as read
for idx, attachment in enumerate(message.attachments):
try:
att_fn = attachment.get('filename')
download_path = f"{download_folder}/{att_fn}"
print(download_path)
with open(download_path, "wb") as fp:
fp.write(attachment.get('content').read())
except:
pass
print(traceback.print_exc())
mail.logout()
解决方案
无法在IMAP中按附件直接搜索。(*BODYSTRUCTURE功能可以获取结构。)
您可以:
- 获取最近5天的电子邮件
- 分析其附件
编码:
import datetime
from imap_tools import MailBox, A
with MailBox('imap.mail.com').login('test@mail.com', 'pwd') as mailbox:
for msg in mailbox.fetch(A(date_gte=datetime.date.today() - datetime.timedelta(days=5))):
print(msg.uid, msg.subject)
for att in msg.attachments:
print(att.filename, len(att.payload))
https://github.com/ikvk/imap_tools 我是作者。
相关文章