0
votes

I have been using the code snippet below to grab every email in a certain subfolder received within the last 3 hours and extract some business information from them before processing, and it has been working great for a week or so. However, yesterday for some reason I noticed it hasn't been working properly, and when I added a print statement to see what emails are sent to the process function I noticed its sending everything from march to the present date (over a 1000 emails).

        outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
        api_folder = outlook.Folders.Item(1).Folders['Some Folder']

        start = datetime.datetime.now() - datetime.timedelta(hours=3)

        # 05/01/2020 05:23 AM is this the right format?

        start = start.strftime('%m/%d/%Y %H:%M %p')

        messages = api_folder.Items.Restrict("[ReceivedTime] >= '" + start + "'")

        # This prints emails that shouldnt be here after Restrict()
        for msg in messages:
            print(f"{msg.Subject} - {msg.ReceivedTime}")

I'm pretty sure it probably is a very dumb mistake in the way Restrict is called or maybe on the time formatting but since I am new to programming I haven't been able to find the root cause of what is making the function misbehave.

Any help is greatly appreciated.

Thanks

1

1 Answers

0
votes

Although dates and times are typically stored with a Date format, the Find and Restrict methods require that the date and time be converted to a string representation. To make sure that the date is formatted as Microsoft Outlook expects, use the strftime (or Format in VBA) function. And make sure Outlook understands it:

api_folder.Items.Restrict("urn:schemas:httpmail:datereceived" >= '9/15/2019 12:00 AM')

Note, you may configure the required filter in Outlook manually to get the string representation and use it in the code.