Search code examples
pythonemailimap

search criteria of IMAP protocol search command


I read from here:

http://docs.python.org/2/library/imaplib.html
IMAP4.search(charset, criterion[, ...])

that imaplib has the search method for me to search mails from my mail boxes.

But I don't understand what criterion are available, or is it that I can enter anything for it?

I searched that page,, but didn't get a clue.


Solution

  • I'm not sure how Python expects the criteria but I'm assuming it's the same as plain IMAP. Refer to the SEARCH command documentation (as larsks already suggested) and use a combination of keywords depending on what you want to retrieve. Examples of criteria:

    SUBJECT Christmas
    

    ...retrieves messages containing "Christmas" in the subject line.

    SUBJECT "New York"
    

    ...retrieves messages containing "New York" (without quotes) in the subject line.

    OR TO boss SUBJECT resignation
    

    ...is to be read as (TO boss) OR (SUBJECT resignation) and will retrieve messages that either have "boss" in the "To" field or contain "resignation" in the subject line.

    As you can see above, IMAP Search uses a prefix notation in its criteria that may at first be confusing. You can reason about them using brackets or else by graphically drawing a tree of criteria - especially useful when you get nested ANDs or ORs.

    There is a fair amount of different criteria you can use. Refer to the RFC for the whole list.

    It may be helpful to interact with IMAP manually (e.g. using telnet) to get used to the structure of SEARCH requests before you spend time coding it.