Related Sites | SpyderMap | Web Portal

Sending HTML Email From Python

I forget where exactly I found this, but the other day I needed a quick Python method to send an HTML email — in my case, it was in response to a Web CGI request, but this example below is usable anywhere.  The bits that need to be changed for different situations should be evident (’somefile.txt’ for example).  You will also need to point the smtplib to an actual mail server if you don’t run one on the local machine.

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 = 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__’:
    f = open(”somefile.html”, “r”)
    html = f.read() % vals
    f.close()
    f = open(”somefile.txt”, ‘r’)
    text = f.read() % vals
    subject = “Some subject”
    message = createhtmlmail(html, text, subject)
    server = smtplib.SMTP(”localhost”)
    server.sendmail(’some_address@somewhere.com’,'to_address@somewhere.com’, message)
    server.quit()

If anyone knows the original source of this example, please tell me and I’ll give proper attributions.

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • Technorati
  • Reddit
Your Ad Here

3 Responses to “Sending HTML Email From Python”

  1. Looks remarkably like (but not identical to) the ‘createhtmlemail’ function from my cgiutils module [1]. I actually adapted this from an IronPython cookbook recipe in the first place - so maybe it came from there.

    Michael

    [1] https://svn.pythonutils.python-hosting.com/trunk/pythonutils/cgiutils.py

  2. I mean Python Cookbook, not IronPython of course. Force of habit. :-)

  3. Upon looking at the cgiutils file, it does in fact look similar. I know I’m not the original author of that code, what I put in the blog entry was a clear cut and paste from somewhere else on the net. The original author probably was influenced by your module.

Leave a Reply