Python IMAP 下载所有附件

我需要将所有邮件迭代到GMAIL收件箱中。另外,我需要下载每封邮件的所有附件(有些邮件有4-5个附件)。我在这里找到了一些帮助:https://stackoverflow.com/a/27556667/8996442


def save_attachments(self, msg, download_folder="/tmp"):

    for part in msg.walk():

        if part.get_content_maintype() == 'multipart':

            continue

        if part.get('Content-Disposition') is None:

            continue


        filename = part.get_filename()

        print(filename)

        att_path = os.path.join(download_folder, filename)

        if not os.path.isfile(att_path):

            fp = open(att_path, 'wb')

            fp.write(part.get_payload(decode=True))

            fp.close()

        return att_path

但是,它每封电子邮件只下载一个附件(但是帖子的作者提到,它基本上下载了所有附件,不是吗?给我看只有一个附件 任何想法为什么?print(filename)


LEATH
浏览 164回答 2
2回答

一只甜甜圈

from imap_tools import MailBox# get all attachments from INBOX and save them to fileswith 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/

慕田峪7331174

正如注释中已经指出的那样,直接的问题是退出循环并离开函数,并且在保存第一个附件后立即执行此操作。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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python