I decided I needed an automatic report of some things on my email every day, and I wanted it to look nice both in plain text and HTML. Here's what I came up with.
Let's assume you created the HTML version using whatever mechanism you wish, and have it in a variable called "report".
Here's the imports 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())