How to set a charset in email using smtplib in Python 2.7?

人走茶凉 提交于 2019-11-28 18:23:06
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def contains_non_ascii_characters(str):
    return not all(ord(c) < 128 for c in str)   

def add_header(message, header_name, header_value):
    if contains_non_ascii_characters(header_value):
        h = Header(header_value, 'utf-8')
        message[header_name] = h
    else:
        message[header_name] = header_value    
    return message

............
msg = MIMEMultipart('alternative')
msg = add_header(msg, 'Subject', subject)

if contains_non_ascii_characters(html):
    html_text = MIMEText(html.encode('utf-8'), 'html','utf-8')
else:
    html_text = MIMEText(html, 'html')    

if(contains_non_ascii_characters(plain)):
    plain_text = MIMEText(plain.encode('utf-8'),'plain','utf-8') 
else:
    plain_text = MIMEText(plain,'plain')

msg.attach(plain_text)
msg.attach(html_text)

This should give you your proper encoding for both text and headers regardless of whether your text contains non-ASCII characters or not. It also means you won't automatically use base64 encoding unnecessarily.

You should encode your message-text with UTF-8

msg = MIMEText(content.encode('utf-8'), text_subtype).

More here: http://radix.twistedmatrix.com/2010/07/how-to-send-good-unicode-email-with.html

You may have to use SMTP header to achieve sending different charsets, try adding this -

msg['Content-Type'] = "text/html; charset=us-ascii"

( Change the charset according to your need )

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!