在Python2.7中,如何解码消息的mime部分并获得**unicode**字符串?

2024-05-15 17:35:42 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是一个尝试获取电子邮件的html部分的方法:

from __future__ import absolute_import, division, unicode_literals, print_function

import email

html_mail_quoted_printable=b'''Subject: =?ISO-8859-1?Q?WG=3A_Wasenstra=DFe_84_in_32052_Hold_Stau?=
MIME-Version: 1.0
Content-type: multipart/mixed;
 Boundary="0__=4EBBF4C4DFD012538f9e8a93df938690918c4EBBF4C4DFD01253"

--0__=4EBBF4C4DFD012538f9e8a93df938690918c4EBBF4C4DFD01253
Content-type: multipart/alternative;
 Boundary="1__=4EBBF4C4DFD012538f9e8a93df938690918c4EBBF4C4DFD01253"

--1__=4EBBF4C4DFD012538f9e8a93df938690918c4EBBF4C4DFD01253
Content-type: text/plain; charset=ISO-8859-1
Content-transfer-encoding: quoted-printable

Freundliche Gr=FC=DFe

--1__=4EBBF4C4DFD012538f9e8a93df938690918c4EBBF4C4DFD01253
Content-type: text/html; charset=ISO-8859-1
Content-Disposition: inline
Content-transfer-encoding: quoted-printable

<html><body>
Freundliche Gr=FC=DFe
</body></html>
--1__=4EBBF4C4DFD012538f9e8a93df938690918c4EBBF4C4DFD01253--

--0__=4EBBF4C4DFD012538f9e8a93df938690918c4EBBF4C4DFD01253--

'''
def get_html_part(msg):
    for part in msg.walk():
        if part.get_content_type() == 'text/html':
            return part.get_payload(decode=True)

msg=email.message_from_string(html_mail_quoted_printable)
html=get_html_part(msg)
print(type(html))
print(html)

输出:

^{pr2}$

不幸的是我得到了一个字节串。我想要unicode字符串。在

根据this answermsg.get_payload(decode=True)应该做的魔术。但在这种情况下,情况并非如此。在

在Python2.7中,如何解码消息的mime部分并获得unicode字符串?在


Tags: textfromimportgethtmltypeunicodeiso
1条回答
网友
1楼 · 发布于 2024-05-15 17:35:42

Unfortunately I get a byte string. I would like to have unicode string.

get_payloaddecode=True参数仅解码Content-Transfer-Encoding包装,即此消息中的=-编码。要从那里获得字符是email包让您自己做的许多事情之一:

bytes = part.get_payload(decode=True)
charset = part.get_content_charset('iso-8859-1')
chars = bytes.decode(charset, 'replace')

iso-8859-1是消息未指定编码时的回退。)

相关问题 更多 >