2011-11-17 273 views
13

這裏MimeText用於當UTF-8編碼的問題是我的代碼,發送電子郵件的一部分:發送電子郵件

servidor = smtplib.SMTP() 
servidor.connect(HOST, PORT) 
servidor.login(user, usenha) 
assunto = str(self.lineEdit.text()) 
para = str(globe_email)    
texto = self.textEdit.toPlainText() 
textos = str(texto) 
corpo = MIMEText(textos.encode('utf-8'), _charset='utf-8') 
corpo['From'] = user 
corpo['To'] = para 
corpo['Subject'] = assunto 
servidor.sendmail(user, [para], corpo.as_string()) 

一切,除了主題的一部分確定。 當我嘗試發送一個字符串包含特殊字符(如「動作類」),它提出了這樣的錯誤:

UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-2: ordinal not in range(128) 

我怎麼能MimeText用於中的主題發送電子郵件有特殊字符?

回答

29

看來,在python3,需要Header對象編碼Subject爲 「UTF-8」:

>>> from email.mime.text import MIMEText 
>>> from email.header import Header 
>>> s = 'ação' 
>>> m = MIMEText(s.encode('utf-8'), 'plain', 'utf-8') 
>>> m['Subject'] = Header(s, 'utf-8') 
>>> m.as_string() 
'Content-Type: text/plain; charset="utf-8"\nMIME-Version: 1.0\nContent-Transfer-Encoding: base64\nSubject: =?utf-8?b?YcOnw6Nv?=\n\nYcOnw6Nv\n' 

所以原來的腳本將變成:

servidor = smtplib.SMTP() 
servidor.connect(HOST, PORT) 
servidor.login(user, usenha) 
assunto = str(self.lineEdit.text()) 
para = str(globe_email)    
texto = str(self.textEdit.toPlainText()) 
corpo = MIMEText(texto.encode('utf-8'), 'plain', 'utf-8') 
corpo['From'] = user 
corpo['To'] = para 
corpo['Subject'] = Header(assunto, 'utf-8') 
servidor.sendmail(user, [para], corpo.as_string()) 
+1

它的工作!我幾乎放棄了......在我提出這個問題之前,我發現了關於Header選項的一些信息,但是我嘗試過的方式沒有奏效,但現在效果很好。真的很感謝你! –

+0

這個解決方案對我來說非常完美。 – alfredocambera

+1

根據文檔,在調用MIMEText時,'.encode('utf-8')'是不必要的。只要指定utf-8編碼,它就會自動編碼unicode:「...如果_text是unicode,則使用_charset的output_charset進行編碼,否則將按原樣使用。經過測試,似乎爲我工作。 – patricksurry