2

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?

DavidH
  • 415
  • 4
  • 21
catdude
  • 33
  • 1
  • 7
  • I'm not positive, but I would try OR (SENTON "X") (SENTON "Y"). Also, some servers have broken search implementations. What server is that? – Max Jan 17 '18 at 20:20
  • Can you please clarify whether you're using imaplib from the standard library or IMAPClient (https://pypi.python.org/pypi/IMAPClient/2.0.0)? – Menno Smits Jan 18 '18 at 08:00
  • I'm using imapclient, not imaplib. – catdude Jan 18 '18 at 13:12
  • Menno, unfortunately the server I'm talking to is Exchange. I'll have a try with your suggestion. – catdude Jan 18 '18 at 13:13
  • >>> data = M.search('OR (SENTON "6-Jan-2018")(SENTON "13-Jan-2018")') Traceback (most recent call last): File "", line 1, in File "/Users/danmahoney/anaconda/lib/python2.7/site-packages/imapclient/imapclient.py", line 725, in search return self._search(criteria, charset) raise self.error('%s command error: %s %s' % (name, typ, data)) imaplib.error: SEARCH command error: BAD ['Command Argument Error. 12'] >>> – catdude Jan 18 '18 at 13:19
  • FWIW, the concrete problem here is/was the doubled space before SENTON. IMAP does not permit extra spaces. It has to be `OR a b`, with exactly one space after OR and exactly one space between a and b. – arnt Nov 11 '19 at 20:17

2 Answers2

1

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'])
Gert-Jan
  • 26
  • 5
1

Try to use query builder:

import datetime as dt
from imap_tools import AND, OR, NOT, Q, H   

# date not in the date list (NOT(date=date1 OR date=date3 OR date=date2))
q2 = NOT(OR(date=[dt.date(2019, 10, 1), dt.date(2019, 10, 10), dt.date(2019, 10, 15)]))
# "NOT ((OR OR ON 1-Oct-2019 ON 10-Oct-2019 ON 15-Oct-2019))"

imap-tools

Vladimir
  • 6,162
  • 2
  • 32
  • 36