July 2002
Intermediate to advanced
608 pages
15h 46m
English
Credit: Art Gillespie
You need to send HTML mail and embed a message version in plain text, so that the message is also readable by MUAs that are not HTML-capable.
The key functionality is supplied by the
MimeWriter and mimetools
modules:
def createhtmlmail(subjectl, html, text=None): "Create a mime-message that will render as HTML or text, as appropriate" import MimeWriter import mimetools import cStringIO if text is None: # Produce an approximate textual rendering of the HTML string, # unless you have been given a better version as an argument import htmllib, formatter textout = cStringIO.StringIO( ) formtext = formatter.AbstractFormatter(formatter.DumbWriter(textout)) parser = htmllib.HTMLParser(formtext) parser.feed(html) parser.close( ) text = textout.getvalue( ) del textout, formtext, parser 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. Place subject here # because smtplib.sendmail expects it to be in the # message body, as relevant RFCs prescribe. 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: just copied through, assuming iso-8859-1 subpart = writer.nextpart( ...Read now
Unlock full access