The imaplib IMAP4 “search” method is very powerful because it allows mail to be filtered on the mail server before ever sending the results back across the network. The following example returns a list of messages numbers for all unread messages newer than the 1st of the year that do not contain “Smith” in the “From” header:
mbox.search(None, 'UNSEEN SINCE 1-Jan-2010 NOT FROM "Smith"')
Like many other IMAP4 object methods, you won’t find the options for this search parameter in the Python imaplib documentation. This is because those parameters are specified in detail inside RFC3501; The Internet Message Access Protocol – Version 4rev1 standard.
RFC’s are great; they’re very detailed, but they were never designed to be user-friendly how-to’s. For example the search string parameter options accepted by IMAP4′s SEARCH command are strewn across five (5) different pages in the RFC and are listed in alphabetical order rather than grouped by function.
For future reference I decided to create an IMAPv4 SEARCH command reference, i.e. cheat-sheet. I’ve grouped the commands by:
- Search for String in Message commands
- Search for Message with Flags Set commands
- Search for Messages with Flags Not Set commands
- Search on Internal Message Date commands
- Search on Message Header Date commands
- Search on Message Size commands
Note: If you use Lotus Notes the mailbox must be full-text indexed before the IMAP4 SEARCH command will work.