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

左心房为你撑大大i 提交于 2021-02-11 12:07:19

问题


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

回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/59394799/how-to-save-ms-outlook-attachments-from-specific-sender-and-date-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!