2

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.

Wolfy
  • 4,213
  • 8
  • 35
  • 42

4 Answers4

4
# 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
                        'html'))

# pipe the mail to sendmail
sendmail = os.popen('sendmail recipient@example.org', 'w')
sendmail.write(message.as_string())
if sendmail.close() is not None:
   print 'error: failed to send mail :-(' 
slowdog
  • 6,076
  • 2
  • 27
  • 30
1

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

Andrey Kuzmin
  • 4,479
  • 2
  • 23
  • 28
0

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

Harish
  • 228
  • 1
  • 7
0

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;
 boundary="123"
Subject: My subject

This is a MIME-encapsulated message

--123
Content-Type: text/html

<html>
   <head>
      <title>HTML E-mail</title>
   </head>
   <body>
      <pre>Some code</pre>
   </body>
</html>

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

Wolfy
  • 4,213
  • 8
  • 35
  • 42