-1

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("example@mydomain.com").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?

  • Maybe you should do the `inbox.Items.Restrict()` call *after* computing the restriction date. As your code stands, in a fresh session that call should give you an undefined local variable error. You are apparently not getting that error, so the variable must be lying around from a previous version of the code. – BoarGules Oct 04 '21 at 19:33

1 Answers1

0

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("example@mydomain.com").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.

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45