Take the 2-minute tour ×

Can someone tell me how to send a mail in a HTML format with sendmail in python?

I would like to send this:

<pre>some code</pre>

Python version is 2.4.3 and can't be updated.

share|improve this question
if smtp is a viable solution you could check docs.python.org/library/email-examples.html –  Poelinca Dorin Feb 15 '11 at 11:06
Possible duplicate - stackoverflow.com/questions/882712/sending-html-email-in-python ? –  Senthil Kumaran Feb 15 '11 at 11:06
not actualy a duplicate since OP is trying to use sendmail and smtp might not be a viable solution . –  Poelinca Dorin Feb 15 '11 at 11:10
smtp is not an option here :S –  Wolfy Feb 15 '11 at 12:12

4 Answers 4

up vote 1 down vote accepted
# assemble the mail content
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
message = MIMEMultipart('alternative')
message.add_header('Subject', 'subject goes here')
# add a few more add_header calls here for things like "To", "Cc", "From"
message.attach(MIMEText('some code')) # plain text alternative
message.attach(MIMEText('<html><pre>some code</pre></html>', # html content

# pipe the mail to sendmail
sendmail = os.popen('sendmail recipient@example.org', 'w')
if sendmail.close() is not None:
   print 'error: failed to send mail :-(' 
share|improve this answer

You may check the code of webpy micro-framework for various methods of sending email, including the sendmail: https://github.com/webpy/webpy/blob/master/web/utils.py#L1415

share|improve this answer

Simply give the HTML code in the message and also mention the mime version and content as text/html. http://www.tutorialspoint.com/python/python_sending_email.htm

share|improve this answer
This is "Sending Email using SMTP" I need to do this with sendmail... –  Wolfy Feb 15 '11 at 12:11

I find a easy way to do this:

When I run my script, I write my output in a file (mail.txt), then at the end, I just call:

os.popen('cat mail.txt | sendmail -t')

mail.txt content:

To: my.mail@gmail.com
MIME-Version: 1.0
Content-Type: multipart/alternative;
Subject: My subject

This is a MIME-encapsulated message

Content-Type: text/html

      <title>HTML E-mail</title>
      <pre>Some code</pre>

Maybe is not the best way to do this, but works fine for me...

share|improve this answer

Your Answer


