2 回答
TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超5個(gè)贊
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貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超13個(gè)贊
正如注釋中已經(jīng)指出的那樣,直接的問題是退出循環(huán)并離開函數(shù),并且在保存第一個(gè)附件后立即執(zhí)行此操作。returnfor
根據(jù)您要完成的確切內(nèi)容,更改代碼,以便僅在完成 的所有迭代時(shí)才更改代碼。下面是一次返回附件文件名列表的嘗試: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
請(qǐng)參閱內(nèi)聯(lián)注釋,了解我更改的內(nèi)容和原因。
一般來說,避免從工人職能內(nèi)部獲取東西;要么用于以調(diào)用方可以控制的方式打印診斷信息,要么僅返回信息并讓調(diào)用方?jīng)Q定是否將其呈現(xiàn)給用戶。print()logging
并非所有 MIME 部件都有 ;實(shí)際上,我希望這會(huì)錯(cuò)過大多數(shù)附件,并可能提取一些內(nèi)聯(lián)部分。更好的方法可能是查看部件是否具有,否則如果不存在或不是,則繼續(xù)提取。也許另請(qǐng)參閱多部分電子郵件中的“部分”是什么?Content-Disposition:Content-Disposition: attachmentContent-Disposition:Content-Type:text/plaintext/html
添加回答
舉報(bào)
