为了账号安全,请及时绑定邮箱和手机立即绑定

Python IMAP 下载所有附件

Python IMAP 下载所有附件

LEATH 2022-08-02 18:27:52
我需要将所有邮件迭代到GMAIL收件箱中。另外,我需要下载每封邮件的所有附件(有些邮件有4-5个附件)。我在这里找到了一些帮助:https://stackoverflow.com/a/27556667/8996442def 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)
查看完整描述

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/


查看完整回答
反对 回复 2022-08-02
?
慕田峪7331174

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


查看完整回答
反对 回复 2022-08-02
  • 2 回答
  • 0 关注
  • 161 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信