【问题标题】:Python IMAP search using a subject encoded with utf-8使用 utf-8 编码的主题的 Python IMAP 搜索
【发布时间】:2012-04-03 17:00:06
【问题描述】:

这个问题与问题Python IMAP search using a subject encoded with iso-8859-1有关,但那里给出的回复对我不起作用。

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

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']

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

【问题讨论】:

  • 这是用普通的 IMAP 服务还是特定的服务器?
  • 先前问题的已接受答案中的代码现在可以使用,我猜你问这个问题时不是这种情况?

标签: python search gmail imap


【解决方案1】:
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')

【讨论】:

  • 我必须这样做 sock.literal = u"réception".encode('utf-8') 才能工作。
【解决方案2】:

u"réception" 需要用引号括起来:u'"réception"',因为 IMAPLIB 不会在列表中为您引用字符串。

更新:我无法让 gmail 的 IMAP 实现接受带引号的字符串,并且必须使用 IMAP 文字语法。我不确定这是我使用 socat 编码的限制,还是 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)

不幸的是,imaplib 没有提供任何强制使用 IMAP 文字的方法。

【讨论】:

    【解决方案3】:

    外部库https://github.com/ikvk/imap_tools支持按编码数据搜索

    from imap_tools import MailBox, A
    
    # get list of emails that subject contains "réception" from INBOX folder
    with MailBox('imap.mail.com').login('test@mail.com', 'pwd') as mailbox:
        for msg in mailbox.fetch(A(subject='réception'), charset='utf8'):
            print(msg.subject)
    

    【讨论】:

      【解决方案4】:

      这个对我有用

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

      谢谢,李!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-04
        • 1970-01-01
        • 2013-03-26
        • 1970-01-01
        • 2012-10-05
        • 1970-01-01
        • 2012-10-17
        相关资源
        最近更新 更多