Search code examples
pythonimapimaplib

why we should write None in imaplib search method


Here is code:

box = imaplib.IMAP4_SSL(HOST,PORT)
box.login(sender,password)
box.select("INBOX")
data = box.search(None, "all")

I can not understand one thing, why I have to write None in search method?every tutorial I have found about using imaplib, says that we should write None but nobody explained why.can somebody give me some information about this?


Solution

  • This is where sometimes reading the documentation is important, as it will tell you more than just the tutorial :

    https://docs.python.org/3.8/library/imaplib.html#imaplib.IMAP4.search

    From the documentation - the signature of the search method is :

    IMAP4.search(charset, criterion[, ...])

    Search mailbox for matching messages. charset may be None, in which case no CHARSET will be specified in the request to the server. The IMAP protocol requires that at least one criterion be specified; an exception will be raised when the server returns an error. charset must be None if the UTF8=ACCEPT capability was enabled using the enable() command.

    So, that says the first argument will be None if either :

    • You don't care what Character set is used during the search or
    • You have specified UTF8=ACCEPT when enabling the Mailbox

    Since you haven't used enable, the first condition applies, and therefore your code snippet is searching the Inbox for all emails with the subject 'all' in any character set.