ASPN ActiveState Programmer Network  
ActiveState, a division of Sophos
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups
Submit Recipe
My Recipes

All Recipes
All Cookbooks


View by Category

Title: Send HTML Mail From Python
Submitter: Art Gillespie (other recipes)
Last Updated: 2001/08/21
Version no: 1.0
Category:

 

5 stars 6 vote(s)


Approved

Description:

After wrestling and wrestling with Outlook 2000 to turn *off* HTML mail, I had to figure out how to send HTML from Python for a recent project. Oh the irony, the irony.

It's good policy (and trivially easy) to embed two versions of your message if you're planning on sending HTML mail: the HTML version, and a text-only version. Lots of folks still prefer their character-mode MUAs (viva Mutt!) so don't go alienating them by sending them something that they can't read.

The e-mails generated by this code have been tested on and render correctly with Outlook 2000, Eudora 4.2, Hotmail, and Netscape Mail. It's likely that they will work in other HTML-capable MUAs as well.

Source: Text Source

def createhtmlmail (html, text, subject):
      	"""Create a mime-message that will render HTML in popular
	   MUAs, text in better ones"""
	import MimeWriter
	import mimetools
	import cStringIO
	
	out = cStringIO.StringIO() # output buffer for our message 
	htmlin = cStringIO.StringIO(html)
 	txtin = cStringIO.StringIO(text)
	
	writer = MimeWriter.MimeWriter(out)
	#
	# set up some basic headers... we put subject here
	# because smtplib.sendmail expects it to be in the
	# message body
	#
	writer.addheader("Subject", subject)
	writer.addheader("MIME-Version", "1.0")
	#
	# start the multipart section of the message
	# multipart/alternative seems to work better
	# on some MUAs than multipart/mixed
	#
	writer.startmultipartbody("alternative")
	writer.flushheaders()
	#
	# the plain text section
	#
	subpart = writer.nextpart()
	subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
	pout = subpart.startbody("text/plain", [("charset", 'us-ascii')])
	mimetools.encode(txtin, pout, 'quoted-printable')
	txtin.close()
	#
	# start the html subpart of the message
	#
	subpart = writer.nextpart()
	subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
	#
	# returns us a file-ish object we can write to
	#
	pout = subpart.startbody("text/html", [("charset", 'us-ascii')])
	mimetools.encode(htmlin, pout, 'quoted-printable')
	htmlin.close()
	#
	# Now that we're done, close our writer and
	# return the message body
	#
	writer.lastpart()
	msg = out.getvalue()
	out.close()
	print msg
	return msg

if __name__=="__main__":
	import smtplib
	f = open("newsletter.html", 'r')
	html = f.read()
	f.close()
	f = open("newsletter.txt", 'r')
	text = f.read()
	subject = "Today's Newsletter!"
	message = createhtmlmail(html, text, subject)
	server = smtplib.SMTP("localhost")
	server.sendmail('agillesp@i-noSPAMSUCKS.com', 'agillesp@i-noSPAMSUCKS.com', message)
	server.quit()

Discussion:

Although the karmic outcome of foisting HTML mail upon the masses is questionable, it seems HTML mail is here to stay. As long as you're conscientious about sending along a plain text version for users who prefer text e-mail, you probably won't get flamed too badly.

The following page http://www.arsdigita.com/asj/mime/ helped me out quite a bit when I was tracking down this problem. Henry Minsky does a good job of sorting out the myriad related RFCs and the fact that there really is no standard for HTML mail.

I hope this is useful. Let me know at agillesp@i-noSPAMSUCKS.com



Add comment

Number of comments: 3

Needs to send To and From headers, Cliff Wells, 2005/10/18
This script is nice, except that it doesn't set the To and From headers which will make some MUA's (Thunderbird for example) show "undisclosed recipients" in the To field. The fix is simple, just pass the sender and recipient to the createhtmlmail() function and add the following two lines to that function:

   writer.addheader("From", sender)
   writer.addheader("To", recipient)

Add comment

How do you add images to HTML Messages?, Richard Him Lok, 2005/11/19
The script is great, but I also need to embed images with the IMG tag into the body of my HTML messages. How do I ensure that they come with them message and are displayed in the correct IMG placeholders? I do not want to rely on an image linked to a file sitting on a server, but carried with the message?
Add comment

HTML with images, too, s g, 2006/09/24
See this recipie: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/473810
Add comment



Highest rated recipes:

1. A simple XML-RPC server

2. Web service accessible ...

3. Treat the Win32 Registry ...

4. Watching a directory ...

5. Union Find data structure

6. Function Decorators by ...

7. MS SQL Server log monitor

8. Table objects with ...

9. wx twisted support using ...

10. More accurate sum




Privacy Policy | Email Opt-out | Feedback | Syndication
© 2006 ActiveState Software Inc. All rights reserved.