简体   繁体   中英

How to save MS Outlook attachments from specific sender and date using Python

I am a bit new to coding and I am trying to understand how to get Python to save MS Outlook attachments from a specific sender. I currently receive the same email from the same person each day regarding data that I need to save to a specific folder. Below are the requirements I am trying to meet:

  1. I want to open MS Outlook and search for specific sender
  2. I want to make sure that the email that I am opening from the specific sender is the most current date
  3. I want to save all attached files from this sender to a specific folder on my desktop

I have seen some posts on using win32com.client but have not had much luck getting it to work with MS Outlook. I will attach some code I have tried below. I appreciate any feedback!

import win32com.client
outlook=win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox=outlook.GetDefaultFolder(6)
messages=inbox.Items
for message in messages:
    attachments = message.attachments
    for attachment in attachments:
        pass

You almost got it, add filter to the sender email address

import win32com.client

Outlook = win32com.client.Dispatch("Outlook.Application")
olNs = Outlook.GetNamespace("MAPI")
Inbox = olNs.GetDefaultFolder(6)

Filter = "[SenderEmailAddress] = '0m3r@email.com'"

Items = Inbox.Items.Restrict(Filter)
Item = Items.GetFirst()

for attachment in Item.Attachments:
    print(attachment.FileName)
    attachment.SaveAsFile(r"C:\path\to\my\folder\Attachment.xlsx")

Python 3.8 on windows

def saveAttachments(email:object):
        for attachedFile in email.Attachments: #iterate over the attachments
                try:
                        filename = attachedFile.FileName
                        attachedFile.SaveAsFile("C:\\EmailAttachmentDump\\"+filename) #Filepath must exist already
                except Exception as e:
                        print(e)

for mailItem in inbox.Items:
        #Here you just need to bould your own conditions
        if mailItem.Sender == "x" or mailItem.SenderName == "y":
               saveAttachments(mailItem)

The actual conditions you can change to your liking. I would recommend referring to the Object model for Outlook MailItem objects: https://docs.microsoft.com/en-gb/office/vba/api/outlook.mailitem Specifically its Properties

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