python win32com.client outlook application is not filtering received emails

1.3k Views Asked by At

I wrote the code as below, but it doesn't do a time filter. what am i doing wrong?

import win32com.client
import os
from datetime import datetime, timedelta

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")

# setup range for outlook to search emails (so we don't go through the entire inbox)
    
received_dt = datetime.now() - timedelta(days=1)
received_dt = received_dt.strftime('%m/%d/%Y %H:%M %p')

# Select main Inbox
inbox = outlook.Folders("[email protected]").Folders("Inboxx")
messages = inbox.Items.Restrict("[ReceivedTime] >= '" + received_dt + "'")


for message in messages:
    print(str(message.ReceivedTime))

I am pasting the output of the code below.

2021-07-05 19:56:03.826000+00:00
2021-09-21 23:13:31.429000+00:00
2021-09-26 22:15:13.527000+00:00
2021-10-03 12:45:04.919000+00:00
2021-10-03 19:43:05.916000+00:00
2021-10-03 20:40:05.875000+00:00

Can you help me please?

1

There are 1 best solutions below

1
Eugene Astafiev On

Try to compute the date and time string before you call the Restrict method:

import win32com.client
import os
from datetime import datetime, timedelta

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")

# setup range for outlook to search emails (so we don't go through the entire inbox)
lastWeekDateTime = dt.datetime.now() - dt.timedelta(days= 7)
lastWeekDateTime = lastWeekDateTime.strftime('%Y-%m-%d %H:%M')  #<-- This format compatible with "Restrict"

received_dt = datetime.now() - timedelta(days=1)
received_dt = received_dt.strftime('%m/%d/%Y %H:%M %p')

# Select main Inbox
inbox = outlook.Folders("[email protected]").Folders("Inboxx")
messages = inbox.Items.Restrict("[ReceivedTime] >= '" + received_dt + "'")

for message in messages:
    print(str(message.ReceivedTime))

Read more about the Restrict method in the How To: Use Restrict method to retrieve Outlook mail items from a folder article.