python smtp没有设置subject / html

时间:2012-01-02 20:47:11

标签: 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 个答案:

答案 0 :(得分: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'

答案 1 :(得分:0)

来自文档:“以下是如何使用其他纯文本版本创建HTML邮件的示例:”http://docs.python.org/library/email-examples.html#id5