Search code examples
pythondateoutlookwin32com

Using Python to Filter Outlook Messages


Can anyone take a look and see if they can tell me why I'm getting messages from yesterday too?

I'm trying to iterate over message items with an attachment from a particular sender if the message was received on/after today, but I seem to be getting message from yesterday too.

Here's how I've set up the messages object:

from datetime import date
import os
import win32com.client

#Win32 Outlook variables 
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
filter_sender= "urn:schemas:httpmail:fromemail='[email protected]'"
filter_attachment = "urn:schemas:httpmail:hasattachment = 1"
filter_date = "urn:schemas:httpmail:datereceived>="+"'"+str(date.today())+"'"
messages = inbox.Items.Restrict(f'@SQL={filter_attachment} And {filter_sender} And {filter_date}' 
)

When tested independently, the filter_sender and filter_attachment work as intended, but when I try filter_date by itself, I'm getting messages from the previous day (yesterday) too.

I gotta be overlooking something here, but I'm not sure what.

Many thanks!


Solution

  • If you are using DASL property names (e.g., "urn:schemas:httpmail:datereceived") rather than OOM (ReceivedTime), the values would be in the UTC time zone - you need to either adjust the value you use in the restriction, or use the OOM name.