如何使用 python IMAP 下载邮件的所有附件

How to download all attachments of a mail using python IMAP

我需要从 outlook 中的特定邮件下载所有附件。 如果只有一个附件,下面的代码工作正常,但当邮件有多个附件时,它只下载一个。 谁能帮我解决这个问题?谢谢

我 运行 在 python 3.7.

import imaplib
import email
import os

server =imaplib.IMAP4_SSL('outlook.office365.com',993)
server.login('Email id','Password')
server.select()
typ, data = server.search(None, '(SUBJECT "Subject name")')
mail_ids = data[0]
id_list = mail_ids.split()

for num in data[0].split():
    typ, data = server.fetch(num, '(RFC822)' )
    raw_email = data[0][1]
    raw_email_string = raw_email.decode('utf-8')
    email_message = email.message_from_string(raw_email_string)

    for part in email_message.walk():
        if part.get_content_maintype() == 'multipart':
            continue
        if part.get('Content-Disposition') is None:
            continue
        fileName = part.get_filename()
        if bool(fileName):
            filePath = os.path.join('C:\Users\lokesing\', fileName)
            if not os.path.isfile(filePath) :
                fp = open(filePath, 'wb')
                fp.write(part.get_payload(decode=True))
                fp.close()
server.logout
print("Attachment downloaded from mail")

输出应该是在定义的路径下下载到我的系统的所有附件。

您可以使用 imap_tools 包: https://pypi.org/project/imap-tools/

from imap_tools import MailBox, Q

# get all attachments for each email from INBOX folder
with MailBox('imap.mail.com').login('test@mail.com', 'password') as mailbox:
    for msg in mailbox.fetch():
        for att in msg.attachments:
            print(att.filename, att.content_type)
            with open('C:/1/{}'.format(att.filename), 'wb') as f:
                f.write(att.payload)

这是使用 Python 从 Outlook 电子邮件下载附件的示例。 我使用了名为:exchangelib 的库。

https://medium.com/@theamazingexposure/accessing-shared-mailbox-using-exchangelib-python-f020e71a96ab

这是代码片段:

from exchangelib import Credentials, Account, FileAttachment
import os.path
from pathlib import Path

credentials = Credentials('Firstname.Lastname@someenterprise.com', 'Your_Password_Here')
account = Account('shared_mail_box_name@someenterprise.com', credentials=credentials, autodiscover=True)
filtered_items = account.inbox.filter(subject__contains='Data is ready for')
print("Getting latest email...")
for item in account.inbox.filter(subject__contains='Data is ready for').order_by('-datetime_received')[:1]:
    print(item.subject, item.sender, item.datetime_received)
    for attachment in item.attachments:
        if isinstance(attachment, FileAttachment):
            filepath = os.path.join('C:\path\to\your\directory', attachment.name)  #this part will download the attachment to local file system
            with open(filepath, 'wb') as f:
                f.write(attachment.content)
            print('Saved attachment to:', filepath)