2012-01-02 47 views
0

出於某種原因,下面的代碼不能正確設置主題字段,並且肯定不會在HTML中呈現電子郵件......即收到電子郵件時,標籤不再出現。python smtp沒有設置主題/ html

謝謝!

def sendEmail (self,remove): 

     message = """From: From Postmaster <%s> 
     To: To Person <%s> 
     MIME-Version: 1.0 
     Content-type: text/html 
     Subject: blahblah 
     <b>This is HTML message.</b> 
     <h1>The following email addresses have been removed</h1> 
     %s 
     """ %(self.sender,self.receivers,remove) 

     smtpObj = smtplib.SMTP('localhost') 
     smtpObj.sendmail(self.sender, self.receivers, message)   
     print "Successfully sent email" 
+2

應該有頭和消息體之間的空行。你有沒有理由不包括?它對你的問題有什麼不同嗎? – SingleNegationElimination 2012-01-02 21:09:19

回答

1

MIME有空格是如何在它的頭文件處理的具體規則。特別是,以空白開頭的行被視爲前一個標題的延續行。在你的例子中,由於每行(在第一行之後)以空白開始,所有內容將被視爲From標題的值。另外,正如@TokenMacGuy指出的那樣,MIME需要在消息頭和消息的有效載荷之間留出一個空行。如果您重新格式化您的消息,則應正確解釋:

message = """From: From Postmaster <%s> 
To: To Person <%s> 
MIME-Version: 1.0 
Content-type: text/html 
Subject: blahblah 

<b>This is HTML message.</b> 
<h1>The following email addresses have been removed</h1> 
%s 
""" %(self.sender,self.receivers,remove) 

應解決您遇到的問題。

或者,你可以使用email包,避免管理的消息自己的格式:

import email.mime.text 

message = """ 
<b>This is HTML message.</b> 
<h1>The following email addresses have been removed</h1> 
%s 
""" % remove 
message = email.mime.text.MIMEText(message, 'html') 
message['From'] = 'From Postmaster <%s>' % sender 
message['To'] = 'To Person <%s>' % receivers[0] 
message['Subject'] = 'blahblah'