我正在尝试在网页中显示电子邮件。该程序是用Python编写的。不幸的是,我有一些字符编码问题。我在文中有引号和双引号。
原邮件:
“All is good”
‘it is getting better’
字符集'windows-1252'我来自ISP:
=93All is good=94
=91it is getting better=92
字符集'utf-8'我来自ISP:
=E2=80=9CAll is good=E2=80=9D
=E2=80=98it is getting better=E2=80=99
我将=..
替换为相应的十六进制字符。然后文本如下:
character set 'windows-1252'
ôAll is goodö
æit is getting betterÆ
character set 'utf-8'
ΓÇ£All is goodΓÇ¥
ΓÇÿit is getting betterΓÇÖ
对unicode函数的后续调用失败,带
UnicodeEncodeError: 'charmap' codec can't encode character u'\u201d' in position 6:
character maps to <undefined>
或类似。
通话看起来像unicode( message, 'utf-8', 'replace' )
。
知道我做错了吗?
答案 0 :(得分:3)
为什么要用任何东西替换任何东西?
>>> m = email.message_from_string('''Content-Type: text/plain; utf-8\nContent-Transfer-Encoding: quoted-printable\n\n=E2=80=9CAll is good=E2=80=9D\n=E2=80=98it is getting better=E2=80=99''')
>>> m.get_payload(decode=True).decode(m['Content-Type'].split('; ')[1])u'\u201cAll is good\u201d\n\u2018it is getting better\u2019'
答案 1 :(得分:0)
因为我试过这个并遇到了问题。这是另一种尝试:
输出如下:
# lines is already prefilled with a valid HTML message
m = email.message_from_string( lines );
email.iterators._structure( m );
print m.is_multipart();
print m.get_payload( decode=True );
print m.get_payload();
输出如下:
&GT;&GT;&GT; execfile('email2.py')
多部分/替代
text / plain的
text / html的
真
无
[&lt; email.message.Message实例位于0x0235FDF0&gt;,&lt; email.message.Message实例位于0x02355F08&gt;]
如果我使用decode='true'
,你会看到失败。这是简化的电子邮件:
Content-Type: multipart/alternative;
boundary="----=_NextPart_000_0130_01CC1E30.41026040"
This is a multi-part message in MIME format.
------=_NextPart_000_0130_01CC1E30.41026040
Content-Type: text/plain;
charset="utf-8"
Content-Transfer-Encoding: quoted-printable
plain
------=_NextPart_000_0130_01CC1E30.41026040
Content-Type: text/html;
charset="utf-8"
Content-Transfer-Encoding: quoted-printable
html
------=_NextPart_000_0130_01CC1E30.41026040--