简体   繁体   English

如何从使用 Python 作为附件发送的电子邮件中下载附件?

[英]How can I download attachments from emails sent as attachments with Python?

I received an email with multiple emails attached.我收到了一封 email,其中附有多封电子邮件。 Each email has.xls file that I want to download.每个email都有我要下载的.xls文件。

How can I do this in Python?我如何在 Python 中执行此操作?

(I use the Outlook app) (我用的是Outlook app)

enter image description here在此处输入图像描述

I tried to move these emails to my inbox and run the code I already use:我试图将这些电子邮件移至我的收件箱并运行我已经使用的代码:

path = 'C:/Users/moliveira/Desktop/projeto_email'
    os.chdir(path)
    output_dir = Path.cwd()
    output_dir.mkdir(parents=True, exist_ok=True)
    outlook = win32com.client.Dispatch("Outlook.Application")
    mapi=outlook.GetNamespace("MAPI")
    inbox = mapi.GetDefaultFolder(6)
    messages = inbox.Items
    received_dt = datetime.now() - BDay(600)
    date_aux = received_dt
    date = received_dt.strftime('%d/%m/%Y')
    Subject = 'OPÇÕES RV - '+date
    received_dt = received_dt.strftime('%m/%d/%Y')

    messages = messages.Restrict("[ReceivedTime] >= '" + received_dt + " 13:00 PM" + "'")
    messages = messages.Restrict("[ReceivedTime] <= '" + received_dt + " 23:59 PM" + "'")


    messages = messages.Restrict("[Subject] = "+Subject)
    try:
        for message in list(messages):
            try:
                s = message.sender
                for attachment in message.Attachments:
                    attachment.SaveASFile(os.path.join(output_dir, attachment.FileName))
                    print(f"attachment {attachment.FileName} from {s} saved")
            except Exception as e:
                print("error when saving the attachment:" + str(e))
    except Exception as e:
            print("error when processing emails messages:" + str(e))        
    date = date_aux.strftime('%d_%m_%Y')
    list(messages)

But the return of list(messages) is empty, meaning that it's not locating the email. I think it's because I have to "click to view more on Microsoft Exchange".但是 list(messages) 的返回是空的,这意味着它没有找到 email。我认为这是因为我必须“单击以在 Microsoft Exchange 上查看更多信息”。 Just after this I can see these emails in the app.在此之后,我可以在应用程序中看到这些电子邮件。 enter image description here在此处输入图像描述

You can save the attached item to the disk and then execute it programmatically to be opened in Outlook (it is a singleton which means only one instance of Outlook can be run at the same time).您可以将附件保存到磁盘,然后以编程方式执行它以在 Outlook 中打开(它是一个 singleton,这意味着只能同时运行一个 Outlook 实例)。

Also if the attached mail item is saved to the disk you may use the NameSpace.OpenSharedItem method which opens a shared item from a specified path or URL. This method is used to open iCalendar appointment (.ics) files, vCard (.vcf) files, and Outlook message (.msg) files.此外,如果附加的邮件项目保存到磁盘,您可以使用NameSpace.OpenSharedItem方法从指定路径或 URL 打开共享项目。此方法用于打开 iCalendar 约会 (.ics) 文件、vCard (.vcf)文件和 Outlook 消息 (.msg) 文件。 So, you will get an instance of the MailItem class which represents the attached Outlook item.因此,您将获得MailItem class 的实例,它表示附加的 Outlook 项目。

TO distinguish Outlook items and regular files attached to the message use the Attachment.Type property which equals to the olEmbeddeditem value when the attachment is an Outlook message format file (.msg) and is a copy of the original message.要区分附加到邮件的 Outlook 项目和常规文件,请使用Attachment.Type属性,当附件是 Outlook 邮件格式文件 (.msg) 并且是原始邮件的副本时,该属性等于olEmbeddeditem值。

If you wants to open them without saving on the disk, see How to Open Outlook file attachment directly not saving it?如果想不存盘打开,请看Outlook文件附件不存盘直接打开怎么办? ( with C# VSTO) . (与 C# VSTO) In short, you can try to read the attached files from the cache folder maintained by Outlook. See Finding Outlook temporary folder for email attachments for more information.简而言之,您可以尝试从 Outlook 维护的缓存文件夹中读取附件。有关更多信息,请参见查找 Outlook 临时文件夹中的 email 附件 Also, you can use a low-level API (Extended MAPI) where you can access the PR_ATTACH_DATA_BIN property, read more about the algorithm in the Opening an attachment article.此外,您可以使用低级 API(扩展 MAPI),您可以在其中访问PR_ATTACH_DATA_BIN属性,请阅读打开附件一文中有关该算法的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM