我正在构建一个系统,该系统使用 Python 的 imaplib
和 email
模块从 gmail 帐户读取电子邮件并获取主题。有时,从 hotmail 帐户收到的电子邮件在其标题中有换行符,例如:
In [4]: message['From']
Out[4]: '=?utf-8?B?aXNhYmVsIG1hcsOtYSB0b2Npbm8gZ2FyY8OtYQ==?=\r\n\t<isatocino22@hotmail.com>'
如果我尝试解码该 header ,它什么也不做:
In [5]: email.header.decode_header(message['From'])
Out[5]: [('=?utf-8?B?aXNhYmVsIG1hcsOtYSB0b2Npbm8gZ2FyY8OtYQ==?=\r\n\t<isatocino22@hotmail.com>', None)]
但是,如果我用空格替换换行符和制表符,它会起作用:
In [6]: email.header.decode_header(message['From'].replace('\r\n\t', ' '))
Out[6]: [('isabel mar\xc3\xada tocino garc\xc3\xada', 'utf-8'), ('<isatocino22@hotmail.com>', None)]
这是 decode_header
中的错误吗?如果不是,我想知道我应该注意哪些其他特殊情况。
最佳答案
这是decode_header
中的一个错误,该错误存在于python2.7中并在python3.3中修复。
>>> sys.version_info
sys.version_info(major=3, minor=3, micro=2, releaselevel='final', serial=0)
>>> email.header.decode_header('=?utf-8?B?aXNhYmVsIG1hcsOtYSB0b2Npbm8gZ2FyY8OtYQ==?=\r\n\t<isatocino22@hotmail.com>')
[(b'isabel mar\xc3\xada tocino garc\xc3\xada', 'utf-8'), (b'<isatocino22@hotmail.com>', None)]
对比
>>> sys.version_info
sys.version_info(major=2, minor=7, micro=5, releaselevel='final', serial=0)
>>> email.header.decode_header('=?utf-8?B?aXNhYmVsIG1hcsOtYSB0b2Npbm8gZ2FyY8OtYQ==?=\r\n\t<isatocino22@hotmail.com>')
[('=?utf-8?B?aXNhYmVsIG1hcsOtYSB0b2Npbm8gZ2FyY8OtYQ==?=\r\n\t<isatocino22@hotmail.com>', None)]
关于Python email.header.decode_header 对多行标题失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20816766/