简体   繁体   中英

How to save MS Outlook attachments from specific folder and hour using Python

I would like to have a Python script to save all the attachements (with their name_datestampfrom a specific folder and filtering for specific timestamp (23:00).

Could you please help me?

I'm using the following code (found in another thread) but it allowes me only to save the attahchement of the most recent mail contained in the Inbox folder with a standard name:

import win32com.client
import os.path


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

Filtermail = "[SenderEmailAddress] = 'xxx@yyy.com'"

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


for attachment in Items.Attachments:
    print(attachment.FileName)
    attachment.SaveAsFile(os.getcwd() + '\\Mail\\' + 'zzzz.xlsx')

First, you need to modify the search condition to get items for a specific time frame.

DateToCheck = "[RecievedTime] >= """ & DateStart & """"  

Second, you need to iterate over all items found in the loop, not just get the first and process attachments (VBA syntax):

Set myRestrictItems = myContacts.Restrict(DateToCheck)  
For Each myItem In myRestrictItems  
    If (myItem.Class = olMail) Then  
       MsgBox myItem.Subject & ": " & myItem.RecievedTime
    End If  
Next  

The MailItem.ReceivedTime property returns a Date indicating the date and time at which the item was received.

Third, here is the search query for items with attachments (VBA syntax):

query ="@SQL=" & chr(34) & "urn:schemas:httpmail:hasattachment" & chr(34) & "=True"

or

query ="@SQL=" & chr(34) & "urn:schemas:httpmail:hasattachment" & chr(34) & "=1"

The samples are in VBA because I am not familiar with Python syntax, but the Outlook object model is common for all kind of programming languages. So, hopefully that shouldn't be a problem.

You can read more about Find / FindNext or Restrict methods in the following articles:

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