0

I'm trying to read outlook emails via python, have code like below:

        import win32com.client
        import os 
        from datetime import datetime, timedelta
        
        outlook = win32com.client.Dispatch('outlook.application')
        mapi = outlook.GetNamespace('MAPI')
        
        messages = mapi.Folders("test@gmail.com").Folders("Inbox").Folders("Test").Items
        

       today_change = timedelta(7)
       today = datetime.today()
       start_date = today - today_change
       start_date = start_date.strftime('%Y-%m-%d %H:%M %p')
       today = today.strftime('%Y-%m-%d %H:%M %p')
        
        messages = messages.Restrict("[ReceivedTime] >= '" + start_date
        + "' And [ReceivedTime] <= '" + today +  "' And  @SQL=(urn:schemas:httpmail:subject LIKE '%deleted%')")

I'm trying to add more filters than 1, but I can't manage to do that. Can someone explain how should I add/merge more filters? Separately they work fine.

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45
KeroN
  • 11
  • 1
  • Since I still coudn't manage to get this work in one phrase, I'm just using: `messages2 = messages.Restrict("[ReceivedTime] >= '" + start_date + "' And [ReceivedTime] <= '" + today + "'") messages2 = messages2.Restrict("@SQL=(urn:schemas:httpmail:subject LIKE '%deleted%')")` and it do the job. – KeroN May 02 '22 at 15:35

2 Answers2

0

@SQL= prefix can only be used to prefix the whole query. Also, it is better to use PR_NORMALIZED_SUBJECT instead of PR_SUBJECT (the former property is what gets indexed).

Try the following (off the top of my head):

messages = messages.Restrict("@SQL=ReceivedTime >= '" + start_date
        + "' And ReceivedTime <= '" + today +  "' And ""http://schemas.microsoft.com/mapi/proptag/0x0E1D001F"" LIKE '%deleted%' ")
Dmitry Streblechenko
  • 62,942
  • 4
  • 53
  • 78
  • Hey, this filter doesn't show any message for me (at least no error tho). And I don't really know what's this link in code. I would be grateful if you could explain a bit more. – KeroN Apr 21 '22 at 17:16
  • It is not a link, it is a DASL property name of the `PR_NORMALIZED_SUBJECT` MAPI property. Try to get rid of the date restriction - do you get back any results? – Dmitry Streblechenko Apr 21 '22 at 17:45
  • Yep, I'm receiving mails with string delete in subject. Still can't find way to get multiple filters at the same time! – KeroN Apr 22 '22 at 12:02
  • Please the actual value of your restriction string with the dates. – Dmitry Streblechenko Apr 22 '22 at 13:44
0

You need to use the SQL syntax in the following way:

messages = messages.Restrict("""@SQL="urn:schemas:httpmail:datereceived" >= '" + start_date
        + "' And "urn:schemas:httpmail:datereceived" <= '" + today +  "' And "urn:schemas:httpmail:subject" LIKE '%deleted%')""")

See Filtering Items Using Query Keywords for more information.

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