Search code examples
python-3.6imaplib

python3 imaplib search function encoding


Can someone point me out how to properly search using imaplib in python. The email server is Microsoft Exchange - seems to have problems but I would want a solution from the python/imaplib side. https://github.com/barbushin/php-imap/issues/128

I so far use:

import imaplib
M = imaplib.IMAP4_SSL(host_name, port_name)
M.login(u, p)
M.select()
s_str = 'hello'
M.search(s_str)

And I get the following error:

>>> M.search(s_str)
('NO', [b'[BADCHARSET (US-ASCII)] The specified charset is not supported.'])

Solution

  • search takes two or more parameters, an encoding, and the search specifications. You can pass None as the encoding, to not specify one. hello is not a valid charset.

    You also need to specify what you are searching: IMAP has a complex search language detailed in RFC3501§6.4.4; and imaplib does not provide a high level interface for it.

    So, with both of those in mind, you need to do something like:

    search(None, 'BODY', '"HELLO"')
    

    or

    search(None, 'FROM', '"HELLO"')