Reputation: 31
I would like to find a note over IMAP using Python3 and it's IMAP extension. I try to search for a subject which contains special chars as in the example below. Is there a way I can encode the search string to be IMAP compatible?
self.connection.search(None, 'ALL', 'SUBJECT "büro"')
returns
UnicodeEncodeError: 'ascii' codec can't encode character '\xfc' in position 10: ordinal not in range(128)
Upvotes: 0
Views: 2674
Reputation: 31
If there are special characters in search string, than literal must be used according to https://www.rfc-editor.org/rfc/rfc3501#page-54. Python imaplib does not do it for search command. So need to use workaround:
imap.literal = subject.encode('UTF-8')
status, data = imap.uid('SEARCH', 'CHARSET UTF-8 SUBJECT')
# fetch is also must be used via uid command after this
without uid version:
imap.literal = subject.encode('UTF-8')
typ, dat = imap._simple_command('SEARCH', "CHARSET UTF-8 SUBJECT")
status, data = imap._untagged_response(typ, dat, 'SEARCH')
Upvotes: 0
Reputation: 21
You should pass UTF-8 encoded string as the search argument and also need to mention "CHARSET UTF-8" in the search query.
some thing like this UID SEARCH CHARSET utf-8 "search string". Here "search string" should be utf-8 encoded.
Upvotes: 2