2014-11-20 29 views
1

發送smtp電子郵件,當我收到電子郵件時,它會顯示純文本版本和html版本。這一點是從Sendgrid接收電子郵件字典,然後將它們發送給另一個用戶。代碼中引用的'message'對象是字典Sendgrid發佈到我的端點。顯示普通版本和HTML版本的Python SMTP電子郵件

這是我所看到的:

test 

Me 
Signature 

    test 

Me 
Signature 

這裏是我發送到郵件服務器字符串:

Content-Type: multipart/mixed; boundary="===============5453410005537724489==" 
MIME-Version: 1.0 
To: [email protected] 
From: Me <[email protected]> 
Subject: test 
reply-to: Original Sender <[email protected]> 

--===============5453410005537724489== 
Content-Type: text/plain; charset="us-ascii" 
MIME-Version: 1.0 
Content-Transfer-Encoding: 7bit 

    test 

Me 
Signature 




--===============5453410005537724489== 
Content-Type: text/html; charset="us-ascii" 
MIME-Version: 1.0 
Content-Transfer-Encoding: 7bit 

<html><head><meta http-equiv="Content-Type" content="text/html charset=us-ascii"></head><body style="word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space;" class=""><span class="Apple-tab-span" style="white-space:pre"> </span>test<br class=""><div apple-content-edited="true" class=""> 
<span>Me</span><br><span>Signature</span> 
</div> 
<br class=""></body></html> 
--===============5453410005537724489==-- 

最後,這裏是Python我使用發送電子郵件:

import smtplib 
from email.MIMEMultipart import MIMEMultipart 
from email.MIMEText import MIMEText 

subject = message.get('subject', 'No Subject') 
text = message.get('text', None) 
html = message.get('html', None) 
to = message.get('to') 
cc = message.get('cc', None) 
reply_to = message.get('from') 

msg = MIMEMultipart() 
msg['To'] = '[email protected]' 
msg['From'] = '[email protected]' 
msg['Subject'] = subject 
msg.add_header('reply-to', reply_to) 

toaddrs = msg['To'] 
if cc is not None: 
    msg['CC'] = ', '.join(cc) 
    toaddrs += ', ' + msg['CC'] 

if text is not None: 
    msg.attach(MIMEText(text[0].encode('ascii', 'ignore'), 'plain')) 
else: 
    msg.attach(MIMEText('No plain text for this email', 'plain')) 

if html is not None: 
    msg.attach(MIMEText(html[0].encode('ascii', 'ignore'), 'html')) 

mailServer = smtplib.SMTP("smtp.gmail.com", 587) 
mailServer.ehlo() 
mailServer.starttls() 
mailServer.ehlo() 
mailServer.login(GMAIL_USERNAME, GMAIL_PASSWORD) 
mailServer.sendmail(GMAIL_USERNAME, toaddrs, msg.as_string()) 
mailServer.quit() 

我在這裏錯過了什麼?

回答

5

您已指定multipart/mixed內容,這意味着這些部分是獨立的消息,並且應該全部按照包括的順序顯示。

你想multipart/alternative,這意味着這些部分是同一個消息的替代版本,只有最後一個接收者能夠理解的內容類型應該被顯示出來。

換句話說:

msg = MIMEMultipart('alternative') 

Wikipedia有不同的亞型多一個很好的解釋,但對於官方定義,轉RFC 2046

5.1.3。混合子類型

「多部分」的「混合」子類型適用於零件是獨立的且需要按特定順序捆綁在一起的零件。 任何實施不認可的「多部分」子類型必須被視爲「混合」子類型的子類型。

5.1.4。替代子類型

「多部分/替代」類型在語法上與 「多部分/混合」相同,但語義不同。特別是, 每個身體部位是同一個 信息的「替代」版本。

系統應該認識到各部分的內容是可互換的 。系統應根據本地環境和參考文獻選擇「最佳」類型,在某些情況下甚至可以通過用戶 進行交互。與「multipart/mixed」一樣,身體部位的順序爲 顯着。在這種情況下,備選方案按照 的順序顯示,以增加對原始內容的忠誠度。一般來說, 最佳選擇是系統本地環境所支持的類型的最後一部分。

「multipart/alternative的」可以使用,例如,在一個奇特的文本格式發送郵件 以這樣一種方式,它可以很容易地在任何地方顯示 ...

+0

驚人的解釋,謝謝。 – Crowson 2014-11-21 02:16:13

相關問題