Python电子邮件 - 8位MIME支持

时间:2016-02-06 21:30:10

标签: python email mime

我正在编写一个简单的MUA应用程序,但我遇到了生成消息的麻烦。

我希望我的程序自动检测SMTP服务器是否支持8bit MIME,如果是,则它会生成一条消息,其中带有纯文本的部分将在8位上编码。在MIME标题中,它应该是这样的:

Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 8bit

主要问题是,python3.4 smtplib没有8-bit encoder,只有base64quoted printable

就我而言,它看起来是:

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
msg = MIMEMultipart()
msg['From'] = 'someone@example.com'
msg['To'] = 'someone@example.com'
msg['Subject'] = 'subject'

text = MIMEText("text here".encode('utf-8'), _charset='utf-8')

msg.attach(text)

# then sending...

text.as_string()调用返回

'Content-Type: text/plain; charset="utf-8"\nMIME-Version: 1.0\nContent-Transfer-Encoding: base64\n\ndGV4dCBoZXJl\n'

此消息非常好,但我希望8-bit包含base64,而不是base64

问题是我真的被定罪使用email.encoders enconding吗?

encode_base64只有encode_quopri.col个功能

1 个答案:

答案 0 :(得分:3)

utf-8的默认主体编码是BASE64,可以在本地替换:

    from email import charset
    ch = charset.Charset('utf-8')
    ch.body_encoding = '8bit'
    text = MIMEText("")
    text.set_charset(ch)
    text.set_payload("text here")
    text.replace_header('Content-Transfer-Encoding', '8bit')
    msg.attach(text)

或全球:

    from email import charset
    charset.add_charset('utf-8', charset.SHORTEST, '8bit')

    text = MIMEText("text here".encode('utf-8'), _charset='utf-8')
    text.replace_header('Content-Transfer-Encoding', '8bit')

    msg.attach(text)
相关问题