Python email.header.decode_header 对多行标题失败

标签 python email

我正在构建一个系统,该系统使用 Python 的 imaplibemail 模块从 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/

相关文章:

python - Perforce - 创建和编辑更改列表

python - 使用 Tornado Python 进行异步函数调用

MySQL通配符匹配两个字段的子字符串

asp.net - 48 小时后在 asp.net 中过期确认电子邮件

node.js - 从 Node.js 使用 AUTH NTLM 访问 SMTP 服务器

python - pyspark 的 "between"函数 : range search on timestamps is not inclusive

python - 如何将 pytest 与子进程一起使用?

python - 如何从 Pandas 数据框中提取列表或字典中的非 NA 值

email - 有没有一种方法可以将TeamCity中构建步骤中的错误添加到电子邮件通知中?

如果电子邮件无效,PHPMailer 不发送