2 回答
TA贡献1836条经验 获得超5个赞
from imap_tools import MailBox
# get all attachments from INBOX and save them to files
with MailBox('imap.my.ru').login('acc', 'pwd', 'INBOX') as mailbox:
for msg in mailbox.fetch():
for att in msg.attachments:
print(att.filename, att.content_type)
with open('/my/{}/{}'.format(msg.uid, att.filename), 'wb') as f:
f.write(att.payload)
https://pypi.org/project/imap-tools/
TA贡献1828条经验 获得超13个赞
正如注释中已经指出的那样,直接的问题是退出循环并离开函数,并且在保存第一个附件后立即执行此操作。returnfor
根据您要完成的确切内容,更改代码,以便仅在完成 的所有迭代时才更改代码。下面是一次返回附件文件名列表的尝试:returnmsg.walk()
def save_attachments(self, msg, download_folder="/tmp"):
att_paths = []
for part in msg.walk():
if part.get_content_maintype() == 'multipart':
continue
if part.get('Content-Disposition') is None:
continue
filename = part.get_filename()
# Don't print
# print(filename)
att_path = os.path.join(download_folder, filename)
if not os.path.isfile(att_path):
# Use a context manager for robustness
with open(att_path, 'wb') as fp:
fp.write(part.get_payload(decode=True))
# Then you don't need to explicitly close
# fp.close()
# Append this one to the list we are collecting
att_paths.append(att_path)
# We are done looping and have processed all attachments now
# Return the list of file names
return att_paths
请参阅内联注释,了解我更改的内容和原因。
一般来说,避免从工人职能内部获取东西;要么用于以调用方可以控制的方式打印诊断信息,要么仅返回信息并让调用方决定是否将其呈现给用户。print()logging
并非所有 MIME 部件都有 ;实际上,我希望这会错过大多数附件,并可能提取一些内联部分。更好的方法可能是查看部件是否具有,否则如果不存在或不是,则继续提取。也许另请参阅多部分电子邮件中的“部分”是什么?Content-Disposition:Content-Disposition: attachmentContent-Disposition:Content-Type:text/plaintext/html
添加回答
举报