Python 电子邮件 - 8 位 MIME 支持

Python email - 8bit MIME support

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

我想让我的程序自动检测SMTP服务器是否支持8bit MIME,如果是,那么它会生成一条消息,其中明文部分将被编码为8位。在 MIME header 中它应该是这样的:

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()调用returns

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

这条消息很好,但我想要 8-bit 结尾,而不是 base64

问题是我真的被定罪使用 base64 enconding 吗?

email.encoders中只有encode_base64encode_quopri函数

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)