Skip to main content

Ralsina.Me — Roberto Alsina's website

Creating and sending nice HTML+Text mails from python

I de­cid­ed I need­ed an au­to­mat­ic re­port of some things on my email ev­ery day, and I want­ed it to look nice both in plain text and HTM­L. Here's what I came up with.

Let's as­sume you cre­at­ed the HTML ver­sion us­ing what­ev­er mech­a­nism you wish, and have it in a vari­able called "re­port".

Here's the im­ports we will use:

import smtplib,email,os,tempfile
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
from email.Charset import Charset

And here's the code:

# Create a HTML mail part
hpart=MIMEText(reporte, _subtype='html', _charset='utf-8')

# Create a plain text mail part
# Ugly and requires links, but makes for a great-looking plain text version ;-)
tf=tempfile.mkstemp()
t=open(tf,'w')
t.write(report)
t.close()
tpart=MIMEText(os.popen('links -dump %s'%tf,'r').read(), _subtype='plain', _charset='utf-8')
os.unlink(tf)

# Create the message with both parts attached
msg=MIMEMultipart('alternative')
msg.attach(hpart)
msg.attach(tpart)

# Standard headers (add all you need, for example, date)
msg['Subject'] = 'Report'
msg['From']    = 'support@yourcompany.com'
msg['To']      = 'you@yourcompany.com'

#If you need to use SMTP authentication, change accordingly
smtp=smtplib.SMTP('mail.yourcompany.com'')
smtp.sendmail('support@yourcompany.com','you@yourcompany.com',msg.as_string())

Contents © 2000-2024 Roberto Alsina