简体   繁体   中英

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

I received an email with multiple emails attached. Each email has.xls file that I want to download.

How can I do this in Python?

(I use the 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". 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).

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. So, you will get an instance of the MailItem class which represents the attached Outlook item.

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.

If you wants to open them without saving on the disk, see How to Open Outlook file attachment directly not saving it? ( with 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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