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
添加回答
舉報