将MIMEText编码为引用的可打印文件 [英] Encode MIMEText as quoted printables
问题描述
Python支持一个功能相当的 MIME-Library ,称为电子邮件。默
。
Python supports a quite functional MIME-Library called email.mime
.
我想要实现的是将包含纯UTF-8文本的MIME部分编码为引用的可打印文件,而不是base64。虽然所有的功能都可以在库中使用,但我并没有使用它:
What I want to achieve is to get a MIME Part containing plain UTF-8 text to be encoded as quoted printables and not as base64. Although all functionallity is available in the library, I did not manage to use it:
示例:
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
最后一个命令导致一个奇怪的消息:
The last command 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
这显然不是编码为引用的打印件,双重传输-encoding
标题最后是奇怪的(如果不是非法的)。
This is obviously not encoded as quoted printables, the double transfer-encoding
header is strange at last (if not illegal).
如何在mime-message中将我的文本编码为引用的打印件?
How can I get my text encoded as quoted printables in the mime-message?
推荐答案
好的,我有一个非常诡异的解决方案,但至少它导致一些方向: MIMEText
假定base64,我不知道如何改变这个。因此,我使用 MIMENonMultipart
:
Okay, I got one solution which is very hacky, but at least it leads into some direction: MIMEText
assumes base64 and I don't know how to change this. For this reason I use 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)
现在消息似乎被正确编码:
Now the message seems to be encoded correctly:
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
甚至可以构建一个隐藏复杂性的新类:
One can even construct a new class which hides the complexity:
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()
这篇关于将MIMEText编码为引用的可打印文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!