Send HTML e-mail in Python?

M

Max

I am looking for some simple example code on generating SMTP e-mail
messages in Python. I have a script that sends system reports to me at
a central e-mail address, and it works fine using smtplib with plain
text messages. I would like to enhance this script to send HTML
formatted messages instead.

Simply sending a text message with HTML tags does not work. The e-mail
client displays the message as plain text with visible <tags>.
 
M

Mike Meyer

Simply sending a text message with HTML tags does not work. The e-mail
client displays the message as plain text with visible <tags>.

You need to add MIME headers to the mail message. I.e., along with the
From: and Subject: lines, add:

MIME-Version: 1.0
Content-Type: text/html

As long as you're using straight ascii, that should be sufficient. If
you want to use extended character sets, things get messy. See <URL:
http://www.cse.ohio-state.edu/cs/Services/rfc/smtplist.html > for the
RFCs you'll want to look at.

<mike
 
S

Steve Holden

Max said:
I am looking for some simple example code on generating SMTP e-mail
messages in Python. I have a script that sends system reports to me at
a central e-mail address, and it works fine using smtplib with plain
text messages. I would like to enhance this script to send HTML
formatted messages instead.

Simply sending a text message with HTML tags does not work. The e-mail
client displays the message as plain text with visible <tags>.

You probably didn't include a "Content-Type: text/html" header in the
RFC822 headers. If that wasn't the problem I do have some code that
works, but I'd have to strip out client-specific features before I
posted it.

regards
Steve
 
M

Max

The solution was I simply missed putting the correct (and
aforementioned) content type in the message header:

msg = ("MIME-Version: 1.0\r\nContent-type: text/html;
charset=utf-8\r\nFrom: %s\r\nTo: %s\r\nSubject: Test Message\r\n" %
(mfrom, mto)) + html
smtp = smtplib.SMTP(smtpserver)
smtp.sendmail(mfrom, mto, msg)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top