jpaires
jpaires

Reputation: 355

Imap search criteria - imaplib (python)

I'm using imaplib for python and I came across a strange behavior. I don't really know if this is an imap ou imaplib problem/feature, so I'm hoping anyone can give me some lights.

During my project I do several searchs on my gmail boxes. Imagine that I do an imap search with the following criteria:

((since "date A") (before "date B"))

Now, if I have emails since "date A", imap(lib) does the expected thing: returns the emails since "date A" and before "data B". Lovely. However, if I have NO emails since "date A", imap(lib) simply ignores that and returns all emails before "date B" even they are not since "data A"!

Is this the expected behavior for imap? I don't really think so, it makes no sense at all.

I really need the ability to search for any given period and I'm hopping not having to pool the box before every search just to know the last email's date.

Any idea? Am I missing something here?

Upvotes: 4

Views: 8361

Answers (2)

Vladimir
Vladimir

Reputation: 6726

You may use imap_tools package: https://pypi.org/project/imap-tools/

Implemented the search logic described in rfc3501.

from imap_tools import A, AND, OR, NOT
# base
mailbox.fetch('TEXT "hello"')  # str
mailbox.fetch(b'TEXT "\xd1\x8f"')  # bytes
mailbox.fetch(A(subject='weather'))  # query, the str-like object
# AND
A(text='hello', new=True)  # 'TEXT "hello" NEW'
# OR
OR(text='hello', date=datetime.date(2000, 3, 15))  # '(OR TEXT "hello" ON 15-Mar-2000)'
# NOT
NOT(text='hello', new=True)  # '(NOT TEXT "hello" NEW)'
# complex:
# 'TO "[email protected]" (OR FROM "[email protected]" TEXT "\\"the text\\"") (NOT (OR UNANSWERED NEW))')
A(OR(from_='[email protected]', text='"the text"'), NOT(OR(A(answered=False), A(new=True))), to='[email protected]')
# encoding
mailbox.fetch(A(subject='привет'), charset='utf8')  # 'привет' will be encoded by MailBox._criteria_encoder

Upvotes: 1

kev
kev

Reputation: 161674

M.search(None, '(since "12-Jul-2010" before "12-Jul-2011")')

  SINCE 
     Messages whose internal date (disregarding time and timezone)
     is within or later than the specified date.

  BEFORE 
     Messages whose internal date (disregarding time and timezone)
     is earlier than the specified date.

  make sure that `SINCE < BEFORE`

Upvotes: 7

Related Questions