使用 utf-8 编码的主题的 Python IMAP 搜索

2022-01-23 00:00:00 python imap gmail search

问题描述

此问题与问题 Python 有关使用 iso-8859-1 编码的主题进行 IMAP 搜索,但那里给出的回复对我不起作用.

This question is related to question Python IMAP search using a subject encoded with iso-8859-1, but the reply given there is not working for me.

我正在 python 中进行以下 IMAP 搜索:

I am doing the following IMAP search in python:

typ, data = self.M.search("utf-8", "(SUBJECT %s)" % u"réception".encode("utf-8"))

我得到以下异常:

...
    typ, data = self.M.search("utf-8", "(SUBJECT %s)" % u"réception".encode("utf-8"))
  File "/usr/local/python/2.7.2/lib/python2.7/imaplib.py", line 625, in search
    typ, dat = self._simple_command(name, 'CHARSET', charset, *criteria)
  File "/usr/local/python/2.7.2/lib/python2.7/imaplib.py", line 1070, in _simple_command
    return self._command_complete(name, self._command(name, *args))
  File "/usr/local/python/2.7.2/lib/python2.7/imaplib.py", line 905, in _command_complete
    raise self.error('%s command error: %s %s' % (name, typ, data))
error: SEARCH command error: BAD ['Could not parse command']

这是为什么呢?我该如何解决这个问题?

Why is that? How can I solve this problem?


解决方案

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

然后:

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

相关文章