13

Python 支持一个非常实用的 MIME 库,称为email.mime.

我想要实现的是获得一个包含纯 UTF-8 文本的 MIME 部分,以编码为带引号的可打印文件,而不是 base64。尽管库中提供了所有功能,但我没有设法使用它:

例子:

import email.mime.text, email.encoders
m=email.mime.text.MIMEText(u'This is the text containing ünicöde', _charset='utf-8')
m.as_string()
# => Leads to a base64-encoded message, as base64 is the default.

email.encoders.encode_quopri(m)
m.as_string()
# => Leads to a strange message

最后一条命令导致一条奇怪的消息:

Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: base64
Content-Transfer-Encoding: quoted-printable

GhpcyBpcyB0aGUgdGV4dCBjb250YWluaW5nIMO8bmljw7ZkZQ=3D=3D

这显然没有编码为引用的可打印文件,双transfer-encoding标头最后很奇怪(如果不是非法的话)。

如何在 mime 消息中将我的文本编码为引用的可打印文件?

4

3 回答 3

13

好的,我得到了一个非常 hacky 的解决方案,但至少它导致了一些方向:MIMEText假设 base64,我不知道如何改变它。出于这个原因,我使用MIMENonMultipart

import email.mime, email.mime.nonmultipart, email.charset
m=email.mime.nonmultipart.MIMENonMultipart('text', 'plain', charset='utf-8')

#Construct a new charset which uses Quoted Printables (base64 is default)
cs=email.charset.Charset('utf-8')
cs.body_encoding = email.charset.QP

#Now set the content using the new charset
m.set_payload(u'This is the text containing ünicöde', charset=cs)

现在消息似乎编码正确:

Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: quoted-printable

This is the text containing =C3=BCnic=C3=B6de

甚至可以构造一个隐藏复杂性的新类:

class MIMEUTF8QPText(email.mime.nonmultipart.MIMENonMultipart):
  def __init__(self, payload):
    email.mime.nonmultipart.MIMENonMultipart.__init__(self, 'text', 'plain',
                                                      charset='utf-8')

    utf8qp=email.charset.Charset('utf-8')
    utf8qp.body_encoding=email.charset.QP

    self.set_payload(payload, charset=utf8qp) 

并像这样使用它:

m = MIMEUTF8QPText(u'This is the text containing ünicöde')
m.as_string()
于 2013-02-18T15:16:21.937 回答
6

在 Python 3 中,您不需要 hack:

import email

# Construct a new charset which uses Quoted Printables (base64 is default)
cs = email.charset.Charset('utf-8')
cs.body_encoding = email.charset.QP

m = email.mime.text.MIMEText(u'This is the text containing ünicöde', 'plain', _charset=cs)

print(m.as_string())
于 2019-08-02T08:16:40.807 回答
5

改编自issue 1525919并在 python 2.7 上测试:

from email.Message import Message
from email.Charset import Charset, QP

text = "\xc3\xa1 = \xc3\xa9"
msg = Message()

charset = Charset('utf-8')
charset.header_encoding = QP
charset.body_encoding = QP

msg.set_charset(charset)
msg.set_payload(msg._charset.body_encode(text))

print msg.as_string()

会给你:

MIME-Version: 1.0
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: quoted-printable

=C3=A1 =3D =C3=A9

另请参阅Python 提交者的此响应

于 2013-05-28T12:57:12.567 回答