【发布时间】:2017-09-06 05:33:24
【问题描述】:
我正在使用 Python 3.6.0b2。
我正在解析很多电子邮件。这封特定的电子邮件是个问题,因为我无法打印电子邮件地址的显示名称。尝试打印电子邮件地址显示名称:
UnicodeEncodeError: 'utf-8' codec can't encode character '\udcc2' in position 30: surrogates not allowed
这是一段测试用例代码,展示了如何重现问题:
(venv3.6) mailripper@ip-10-0-0-112:/opt/mailripper$ cat test.py
from email import policy
from email.headerregistry import Address
from email.parser import BytesHeaderParser, BytesParser
email_bytes = b'From: =?utf-8?Q?John_Smith=2C_Prince2=C2=AE=2CPMP=C2=AE=2C_CSM=C2?=\r\n =?utf-8?Q?=AE=2C_ITIL=C2=AE=2C_ISTQB=C2=AE?= <jon.smith@example.org>\r\n'
msg = BytesHeaderParser(policy=policy.default).parsebytes(email_bytes)
print(msg['from'])
print(msg['from'].addresses[0].display_name)
这是上面代码产生的错误:
(venv3.6) mailripper@ip-10-0-0-112:/opt/mailripper$ python test.py
"John Smith, Prince2®,PMP®, CSM� �, ITIL®, ISTQB®" <jon.smith@example.org>
Traceback (most recent call last):
File "test.py", line 8, in <module>
print(msg['from'].addresses[0].display_name)
UnicodeEncodeError: 'utf-8' codec can't encode character '\udcc2' in position 30: surrogates not allowed
这是在 OSX 电子邮件客户端中显示的显示名称,它似乎可以解析它(这是一个屏幕截图,裁剪得很小):
我的目标是能够在没有 unicode 错误的情况下处理任何电子邮件,并且无需编写自定义 unicode 错误处理代码 - 这可能吗?
谁能建议我可以做些什么来避免在显示电子邮件地址显示名称时出现 Unicode 错误?
【问题讨论】:
标签: python email unicode utf-8 mime