您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何在Python 2.7中使用smtplib在电子邮件中设置字符集?

如何在Python 2.7中使用smtplib在电子邮件中设置字符集?

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)

无论您的文本是否包含非ASCII字符,这都应该为您提供适当的文本和标题编码。这也意味着您不会不必要地自动使用base64编码。

python 2022/1/1 18:33:55 有217人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶