Chapter 15 ■ IMap
284
Searching
Searching is another feature that is very important for a protocol designed to let you keep all of your e-mail on the
e-mail server itself: without search, an e-mail client would have to download all of a user’s e-mail anyway the first
time they wanted to perform a full-text search to find an e-mail message.
The essence of search is simple: you call the search() method on an IMAP client instance, and you are returned
the UIDs (assuming, of course, that you accept the IMAPClient default of use_uid=True for your client) of the
messages that match your criteria:
c.select_folder('INBOX')
c.search('SINCE 13-Jul-2013 TEXT Apress')
[2590L, 2652L, 2653L, 2654L, 2655L, 2699L]
These UIDs can then be the subject of a fetch() command that retrieves the information about each message
you need in order to present a summary of the search results to the user.
The query shown in the foregoing example combines two criteria: one requesting recent messages (those that
have arrived since July 13, 2013, the date on which I am typing this) and the other asking that the message text
have the word Apress somewhere inside, and the results will include only messages that satisfy the first criteria and
the second criteria—that is the result of concatenating two criteria with a space so that they form a single string. If
instead you wanted messages that match at least one of the criteria, but did not need to match both, you can join the
criteria with an OR operator:
OR (SINCE 20-Aug-2010) (TEXT Apress)
There are many criteria that you can combine in order to form a query. Like the rest of IMAP, they are specified in
RFC 3501. Some criteria are quite simple and refer to binary attributes like flags:
ALL: Every message in the mailbox
UID (id, ...): Messages with the given UIDs
LARGER n: Messages more than n octets in length
SMALLER m: Messages less than m octets in length
ANSWERED: Have the flag \Answered
DELETED: Have the flag \Deleted
DRAFT: Have the flag \Draft
FLAGGED: Have the flag \Flagged
KEYWORD flag: Have the given keyword flag set
NEW: Have the flag \Recent
OLD: Lack the flag \Recent
UNANSWERED: Lack the flag \Answered
UNDELETED: Lack the flag \Deleted
UNDRAFT: Lack the flag \Draft
UNFLAGGED: Lack the flag \Flagged
UNKEYWORD flag: Lack the given keyword flag
UNSEEN: Lack the flag \Seen