Python IMAPClient / imaplib搜索unicode问题

时间:2013-08-05 09:08:11

标签: python google-app-engine gmail-imap imaplib

我正在使用IMAPClient库,但在进行搜索时我得到UnicodeEncodeError。下面是一个片段和堆栈跟踪:

imap_client = imapclient.IMAPClient('imap.gmail.com', use_uid=True, ssl=True)
imap_client.oauth2_login('john@example.com', 'xxx')
subject = u'Test \u0153\u2211\u00b4\u00e5\u00df\u2202'
from_email = u'john@example.com'
to_emails = [u'foo@example.com']
cc_emails = []
approx_date_sent = '05-Aug-2013'

imap_client.select_folder(r'\Sent')
search_criteria = [
   u'FROM %s' % from_email,
   u'SUBJECT %s'.encode('utf-8') % subject,
   u'TO %s' % ';'.join(to_emails) or '',
   u'CC %s' % ';'.join(cc_emails) or '',
   u'SENTON %s' % approx_date_sent
]
msg_ids = imap_client.search(search_criteria, charset='utf-8')

'ascii' codec can't encode characters in position 77-82: ordinal not in range(128)
Traceback (most recent call last):
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.1/webapp2.py", line 570, in dispatch
    return method(*args, **kwargs)
  File "/base/data/home/apps/s~app/dev.369284735686497536/imapapi.py", line 269, in post
    to_emails=to_emails, cc_emails=cc_emails, approx_date_sent=approx_date_sent
  File "/base/data/home/apps/s~app/dev.369284735686497536/utils/imap.py", line 123, in search_message
    msg_ids = imap_client.search(search_criteria, charset='utf-8')
  File "/base/data/home/apps/s~app/dev.369284735686497536/imapclient/imapclient.py", line 569, in search
    typ, data = self._imap.search(charset, *criteria)
  File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/imaplib.py", line 625, in search
    typ, dat = self._simple_command(name, 'CHARSET', charset, *criteria)
  File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/imaplib.py", line 1070, in _simple_command
    return self._command_complete(name, self._command(name, *args))
  File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/imaplib.py", line 857, in _command
    self.send('%s%s' % (data, CRLF))
  File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/imaplib.py", line 1178, in send
    sent = self.sslobj.write(data)
  File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/ssl.py", line 232, in write
    return self._sslobj.write(data)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 77-82: ordinal not in range(128)

问题似乎发生在ssl.pyssl=True需要oauth2_login

1 个答案:

答案 0 :(得分:0)

试试这个

Python IMAP search using a subject encoded with iso-8859-1

它涵盖了utf-8以及iso-8859-1