Outlook mail restriction on current date

Viewed 61

I am doing automation on the manual work where I am reading the data from outlook mail using win32.

But I need to read mail restrict on the current date otherwise won't read the mail. If mail is not there on a current date then it will skip this part. Below are the codes that compare the received date and today but getting the error.

outlook = win32.Dispatch("Outlook.Application").GetNamespace("MAPI")

folder = outlook.GetDefaultFolder(6)

messages = folder.Items
messages.Sort("[ReceivedTime]", True)
CurrentDateTime = dt.datetime.now()
CurrentDateTime = CurrentDateTime.strftime('%m/%d/%Y %H:%M %p')
messages = messages.Restrict("[ReceivedTime] == '" + CurrentDateTime +"'")
print(messages)
for m in messages:
    if m.Subject.startswith('Daily SSC count to SD Team'):
        m1=m.Body
        print(m1)
        break;

Error:

File "<COMObject <unknown>>", line 2, in Restrict
pywintypes.com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', 'Cannot parse condition. Error at "=".', None, 0, -2147352567), None)
2 Answers

It should be only one = not two == try itItems.Restrict method (Outlook) it should give you current date and time

Example

messages = messages.Restrict("[ReceivedTime] = '" + CurrentDateTime +"'")

But if your are trying to set the filter for 24 hours then start with today's date with time 00:00 then use >= on current_date = dt.date.today()

full example

import win32com.client
import datetime as dt


def outlook_email(Inbox):
    current_date = dt.date.today()
    print(current_date)
    
    current_date = current_date.strftime("%m/%d/%Y %H:%M")
    print(current_date)
    
    items = Inbox.Items.Restrict("[ReceivedTime]>='" + current_date + "'")
    print(items.Count)


if __name__ == "__main__":
    outlook = win32com.client.Dispatch(
        "Outlook.Application").GetNamespace(
        "MAPI"
    )

    inbox = outlook.GetDefaultFolder(6)
    outlook_email(inbox)

Never use = when working with date/time properties - the condition will never be satisfied even if the value (both date and time) matches that of an existing message because of round-off errors.

Always use a range (< and >), or (if you are dealing with the current date and assume there won't be any messages with a newer date), use >= as @0m3r suggested.

Related