【问题标题】:How to download all attachments of a mail using python IMAP如何使用 python IMAP 下载邮件的所有附件
【发布时间】:2019-10-10 10:02:13
【问题描述】:

我需要从 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")

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

【问题讨论】:

  • 如果某个答案对您有用,最好投票赞成答案 =)

标签: python-3.x imap email-attachments


【解决方案1】:

你可以使用 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)

【讨论】:

  • 谢谢@Vladimir。我将在星期一尝试,并让您知道我的输出。再次感谢。
  • 嗨@弗拉基米尔。我能够使用 imap_tools 下载所有附件。 from imap_tools import MailBox, Q import os with MailBox('outlook.office365.com').login('Email id', 'Password') as mailbox: for message in mailbox.fetch(): if message.subject == "检查多个附件”:对于名称,message.attachments 中的有效负载:filePath = os.path.join('C:\\Users\\lokesing\\', name) fp = open(filePath, 'wb') fp.write (payload) fp.close() 感谢您的帮助
【解决方案2】:

这是一个使用 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-19
    • 1970-01-01
    • 1970-01-01
    • 2011-09-06
    • 2017-10-15
    • 2020-09-27
    • 2012-04-15
    • 1970-01-01
    相关资源
    最近更新 更多