2014-02-19 24 views
1

我正在嘗試編寫一個腳本,用於從網站上刪除一些文本,然後通過電子郵件將所述文本發送給我。將提取的BeautifulSoup文本編碼爲電子郵件

除編碼之外,它都可以按照需要工作。該電子郵件包含如下行:

我們說,呃,它現在全部結束了,什麼是

顯然,「???」應該是撇號。我不太熟悉編碼的複雜性,特別是當它涉及到電子郵件,所以任何幫助將不勝感激。我的腳本的相關部分是如下:

msg = MIMEMultipart() 
msg['From'] = fromaddr 
msg['To'] = toaddrs 
msg['Subject'] = "Daily Utmost Devo" 

# webtext, cleanverse, & cleanlink are all <type 'unicode'> at this point 

body = webtext.encode('utf-8') 
bodyverse = cleanverse.encode('utf-8') 
bodylink = cleanlink.encode('utf-8') 
msg.attach(MIMEText(body, 'plain')) 
msg.attach(MIMEText(bodyverse, 'plain')) 
msg.attach(MIMEText(bodylink, 'plain')) 

username = '[email protected]' 
password = 'xxxxx' 

server = smtplib.SMTP('smtp.gmail.com:587') 
server.ehlo() 
server.starttls() 
server.ehlo() 
server.login(username, password) 
text = msg.as_string() 
server.sendmail(fromaddr, toaddrs, text) 
server.quit() 

回答

0

MimeText需要_charset參數:

類email.mime.text.MIMEText(_text [,_subtype [,_CHARSET]])

模塊:email.mime.text

MIMENonMultipart的子類,MIMEText類用於創建 主要類型文本的MIME對象。 _text是有效負載的字符串。 _subtype是次要類型,默認爲plain。 _charset是文本的字符集,並作爲參數傳遞給MIMENonMultipart構造函數;它默認爲us-ascii。如果_text是 unicode,則使用_charset的output_charset進行編碼,否則使用原來的 。

版本2.4中已更改:先前已棄用的_encoding參數 已被刪除。內容傳輸編碼現在基於_charset參數隱式發生 。

除非將_charset參數明確設置爲None,否則創建的MIMEText對象將同時具有帶字符集 參數的Content-Type標頭和Content-Transfer-Endcoding標頭。這意味着即使在set_payload命令中傳遞了字符集,後續set_payload調用也不會產生編碼的有效內容,即 。您可以通過刪除Content-Transfer-Encoding 頭來「重置」此行爲,此後set_payload調用將自動編碼 新的有效負載(並添加新的Content-Transfer-Encoding標頭)。

所以儘量

msg.attach(MIMEText(body, 'plain', 'utf-8')) 
msg.attach(MIMEText(bodyverse, 'plain', 'utf-8')) 
msg.attach(MIMEText(bodylink, 'plain', 'utf-8')) 

編輯也看到這些帖子

MIMEText UTF-8 encode problems when sending email

Python - How to send utf-8 e-mail?

Encoding of headers in MIMEText

+0

謝謝!完美工作。作爲一個便箋,你知道在接收電子郵件中格式化文本的任何資源(即字體,大小等)嗎?再次感謝你。 – Extinct23

+0

@ Extinct23你應該看看HTML格式。電子郵件允許同時發送電子郵件的HTML格式和純文本版本。我不知道Python是如何處理這個的 –