IMAP如何保存“所有**”附件

时间:2018-10-05 17:58:30

标签: python email-attachments imaplib

我正在尝试将收件箱中的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')

1 个答案:

答案 0 :(得分:0)

  

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

实施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:附件显式标记为附件),然后返回所有其余部分。   

使用的模块和类:
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: