Search code examples
pythonsearchimapimapclient

Python imapclient search using multiple operands


I am using Python's imapclient, and I need to be able to search on multiple operands. For example, let's say that I want to see messages sent on Jan 6, 2018 or on Jan 13, 2018. I've looked at IMAP criteria with multiple ORs and at https://www.limilabs.com/blog/imap-search-requires-parentheses.

Using tips from that last reference, I've tried:

*r_data = M.search(['OR SENTON "6-Jan-2018"  SENTON "13-Jan-2018"'])
r_data = M.search('OR SENTON "6-Jan-2018"  SENTON "13-Jan-2018"')
r_data = M.search('SENTON "6-Jan-2018" OR SENTON "13-Jan-2018"')*

and a couple others. Each time I get:

*imaplib.error: UID command error: BAD ['Command Argument Error. 11']*

I'd really rather not have to dig into the imapclient code to work out how to structure this request. Does anyone have any suggestions?


Solution

  • I came across the same issue. Found the solution to be (based upon comments in the source code):

    r_data = M.search(['OR', 'SENTON', '6-Jan-2018', 'SENTON', '13-Jan-2018'])
    

    or maybe even better:

    r_data = M.search(['OR', 'SENTON', date(2018, 1, 6), 'SENTON', date(2018, 1, 13)])
    

    Also works for more complex queries like:

    M.search(['OR', 'OR', 'FROM', 'a', 'FROM', 'b', 'FROM', 'c'])