Python IMAP search using a subject encoded with utf-8

依然范特西╮ 提交于 2019-12-01 09:16:05
import imaplib
import getpass
email = "XXXXXXX@gmail.com"

sock = imaplib.IMAP4_SSL("imap.gmail.com", 993)
sock.login(email, getpass.getpass())

# select the correct mailbox...
sock.select()
# turn on debugging if you like
sock.debug = 4

then:

# use the undocumented IMAP4.literal attribute
sock.literal = "réception"
sock.uid('SEARCH', 'CHARSET', 'UTF-8', 'SUBJECT')

u"réception" will need to be wrapped with quotes: u'"réception"', as IMAPLIB will not quote the string for you in the list.

Update: I could not get gmail's IMAP implementation to accept even a quoted string, and had to use IMAP literal syntax. I'm not sure if this is limitation of my encoding using socat, or a limitation with gmail.

a UID SEARCH CHARSET utf-8 SUBJECT "réception"
a BAD Could not parse command

a UID SEARCH CHARSET utf-8 SUBJECT {10}
+ go ahead
réception
* SEARCH
a OK SEARCH completed (Success)

Unfortunately, imaplib does not provide any way to force using of an IMAP literal.

this one works for me

# use the undocumented IMAP4.literal attribute
sock.literal = u"réception".encode('utf-8')
sock.uid('SEARCH', 'CHARSET', 'UTF-8', 'SUBJECT')

Thanks, Lee!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!