Cmag
Cmag

Reputation: 15770

python smtp not setting subject/html

for some reason the following code does not set the Subject field properly, and certainly does not render the email in HTML... ie, the and tags are gone when email is received.

Thanks!

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"

Upvotes: 0

Views: 505

Answers (2)

DRH
DRH

Reputation: 8356

MIME has specific rules for how whitespace is handled in its headers. In particular, lines that begin with whitespace are treated as continuation lines for the previous header. In your example, since each line (after the first) begins with whitespace, all of the content will be treated as the value of the From header. In addition, as @TokenMacGuy pointed out MIME requires a blank line between the headers and the payload of the message. If you reformat your message follows, it should be interpreted correctly:

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)

Should address the problems you're seeing.

Alternatively, you could use the email package and avoid managing the format of the message yourself:

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'

Upvotes: 1

sgallen
sgallen

Reputation: 2109

From the docs: "Here’s an example of how to create an HTML message with an alternative plain text version:" http://docs.python.org/library/email-examples.html#id5

Upvotes: 0

Related Questions