【问题标题】:IMAP how to save **all** attachmentsIMAP 如何保存**所有**附件
【发布时间】:2019-03-11 06:44:16
【问题描述】:

我正在尝试将我的收件箱中的 excel 文件附件保存到一个目录中。我的代码执行得很好,因为我看到了打印输出,但附件不会保存在文件目录中。我的代码中是否缺少阻止保存操作的内容?

 import email, getpass, imaplib, os, sys


detach_dir = r'\directory link'

user = "test"
pwd = "test"
sender_email = "example@example.com"

m = imaplib.IMAP4_SSL("outlook.office365.com")
m.login(user,pwd)


m.select('"INBOX/somestuff"')

print("ok")



resp, items = m.search(None, 'FROM', '"%s"' % sender_email)
items = items[0].split()

print("ok")

for emailid in items:
    resp, data = m.fetch(emailid, "(RFC822)")
    email_body = data[0][1].decode('utf-8')
    mail = email.message_from_string(email_body)

    print("ok")

    if mail.get_content_maintype() != 'multipart':
        continue



    subject = ""

    if mail["subject"] is not None:
        subject = mail["subject"]

    print ("["+mail["From"]+"] :" + subject)

    for part in mail.walk():
        if part.get_content_maintype() == 'multipart':
            continue

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

        filename = part.get_filename()
        counter = 1

        if not filename:
            filename = 'part-%03d%s' % (counter, 'bin')
            counter += 1

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

        if not os.path.isfile(att_path) :
            fp = open(att_path, 'wb')
            fp.write(part.get_payload(decode=True))
            fp.close()

此代码仅将其中一个附件保存在子文件夹中,但我希望将所有附件保存到目录中:

detach_dir = r'directory link'
m = imaplib.IMAP4_SSL("outlook.office365.com")
m.login('user','pass')
m.select('"INBOX/subfolder"')

resp, items = m.search(None, 'All')
items = items[0].split()

for emailid in items:
    resp, data = m.fetch(emailid, "(RFC822)") 
    filename = part.get_filename()
    print(filename)
    att_path = os.path.join(detach_dir, filename)
    fp = open(att_path, 'wb')
    fp.write(part.get_payload(decode=True))
    fp.close()

    print('check folder')

【问题讨论】:

    标签: python email-attachments imaplib


    【解决方案1】:

    问题:此代码仅保存一个附件...但我希望获得所有附件

    实现iter-attachments()

    resp, items = imap.search(None, "(UNSEEN)")
    
    for n, num in enumerate(items[0].split(), 1):
        resp, data = imap.fetch(num, '(RFC822)')
    
        data01 = data[0][1]
        msg_obj = email.message_from_string(data01)
    
        for part in msg_obj.iter_attachments():
            filename = part.get_filename()
            print(filename)
    

    iter_attachments()

    返回一个迭代器,遍历所有不是候选“正文”部分的消息直接子部分。也就是说,跳过 text/plain、text/html、multipart/related 或 multipart/alternative 中每一个的第一次出现(除非它们通过 Content-Disposition: attachment 明确标记为附件),并返回所有剩余部分。

    使用的模块和类:
    class imaplib.IMAP4 class email.message.EmailMessage

    Here’s an example of how to unpack a MIME message, using email.message.walk(), into a directory of files:

    【讨论】:

    • 该功能无法识别。你有一个完整的脚本吗?也许我错过了什么。
    • @orangecodelife:更新了我的答案。显示您的 Python 版本。
    • 我使用的版本是 Python 3
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-11
    • 2015-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    相关资源
    最近更新 更多