19

我正在编写一个带有身份验证的简单 smtp 发件人。这是我的代码

    SMTPserver, sender, destination = 'smtp.googlemail.com', 'user@gmail.com', ['reciever@gmail.com']
    USERNAME, PASSWORD = "user", "password"

    # typical values for text_subtype are plain, html, xml
    text_subtype = 'plain'


    content="""
    Hello, world!
    """

    subject="Message Subject"

    from smtplib import SMTP_SSL as SMTP       # this invokes the secure SMTP protocol (port 465, uses SSL)
    # from smtplib import SMTP                  # use this for standard SMTP protocol   (port 25, no encryption)
    from email.MIMEText import MIMEText

    try:
        msg = MIMEText(content, text_subtype)
        msg['Subject']=       subject
        msg['From']   = sender # some SMTP servers will do this automatically, not all

        conn = SMTP(SMTPserver)
        conn.set_debuglevel(False)
        conn.login(USERNAME, PASSWORD)
        try:
            conn.sendmail(sender, destination, msg.as_string())
        finally:
            conn.close()

    except Exception, exc:
        sys.exit( "mail failed; %s" % str(exc) ) # give a error message

它工作完美,直到我尝试发送非 ascii 符号(俄语西里尔文)。我应该如何在消息中定义字符集以使其以正确的方式显示?提前致谢!

UPD。我改变了我的代码:

text_subtype = 'text'
content="<p>Текст письма</p>"
msg = MIMEText(content, text_subtype)
msg['From']=sender # some SMTP servers will do this automatically, not all
msg['MIME-Version']="1.0"
msg['Subject']="=?UTF-8?Q?Тема письма?="
msg['Content-Type'] = "text/html; charset=utf-8"
msg['Content-Transfer-Encoding'] = "quoted-printable"
…
conn.sendmail(sender, destination, str(msg))

所以,我第一次指定 text_subtype = 'text',然后在标题中放置一个 msg['Content-Type'] = "text/html; charset=utf-8" 字符串。这是正确的吗?

更新最后,我解决了我的消息问题你应该像 msg = MIMEText(content.encode('utf-8'), 'plain', 'UTF-8') 这样写

4

3 回答 3

26
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 编码。

于 2013-01-24T17:06:03.890 回答
5

您应该使用 UTF-8 编码您的消息文本

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

更多信息: http ://radix.twistedmatrix.com/2010/07/how-to-send-good-unicode-email-with.html

于 2012-04-24T11:42:49.433 回答
2

您可能必须使用 SMTP 标头来实现发送不同的字符集,尝试添加这个 -

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

(根据需要更改字符集)

于 2012-04-24T10:15:17.840 回答