2012-04-24 66 views
12

我正在寫一個簡單的驗證smtp發件人。這是我的代碼如何在Python 2.7中使用smtplib在電子郵件中設置字符集?

SMTPserver, sender, destination = 'smtp.googlemail.com', '[email protected]', ['[email protected]'] 
    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)) 

所以,我第一次spectify text_subtype = '文本',然後在頭我把一個味精[ '內容類型'] =「text/html的;字符集= UTF -8「字符串。這是對的嗎?

UPDATE最後,我已經解決了我的問題的消息 你應該寫像味精=未便MimeText用於(content.encode( 'UTF-8'), '普通', 'UTF-8')

回答

19
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:應使用UTF-8

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

這裏更多編碼您的郵件文本字符或不是。這也意味着你不會不必要地自動使用base64編碼。

+0

嗨Lorcan!如果我要在我的消息中指定它們(比如msg ['From'] ='[email protected]'),那麼'To'和'From'如何?我應該對它進行編碼呢? – 2017-10-24 12:26:12

1

您可能需要使用SMTP頭實現發送不同的字符集,你可以添加以下 -

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

(根據您的需要更改字符集)

+0

那麼,這對我工作 - 主題是以適當的方式顯示,雖然消息文本編碼仍然不妥。 – f1nn 2012-04-24 10:57:42

+0

我已更新我的帖子。請你可以看看新的 – f1nn 2012-04-24 11:00:55

相關問題