I have the following code but could not get it to filter correctly using datetime range. I saw some solution to use a loop and compare the ReceivedTime which has been converted to datetime, but that is not what I want. I would like to first check the folder for number of filtered emails (unread emails within a specific datetime range). If the number of filtered emails meet a certain criteria, then I will proceed to loop each filtered email. Appreciate if anyone has any ideas how to do this:
# Import
import win32com.client
import win32com
import os
import sys
import datetime
# Open Microsoft Outlook
outlook = win32com.client.Dispatch('Outlook.Application')
# Set Outlook Folder Name
inbox = outlook.GetNamespace('MAPI').GetDefaultFolder(6)
folder = inbox.Folders['FilteredFolder']
# Set Outlook date filter
sFilter = "[ReceivedTime]>'{0}".format((datetime.datetime.today() - datetime.timedelta(hours=2)).strftime("%y-%m-%d %H:%M:%S")) + "'" # Lower datetime bound
sFilter2 = "[ReceivedTime]<'{0}".format((datetime.datetime.today()).strftime("%y-%m-%d %H:%M:%S")) + "'" # Upper datetime bound
messages = folder.Items.Restrict('[Unread] = True') # Restrict for Unread emails
messages = messages.Restrict(sFilter) # Restrict the datetime lower bound
messages = messages.Restrict(sFilter2) # Restrict the datetime upper bound
no_of_messages = len(messages) # Mail count
print(str(no_of_messages))