Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Python HTML Email Sender
<html xmlns="">
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<body style="text-align:center">
<table width="600" style="margin:0 auto; text-align: left">
<h1>Python HTML Emailer</h1>
Hello, {{name}}
import smtplib, os, inspect
from jinja2 import Template
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
email_template = None
# Assumes 'email.tpl.html' is in the same folder as this file
email_template_path = os.path.join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))), 'email.tpl.html')
with open(email_template_path,'rU') as tfile:
email_template = Template('utf-8', 'replace'))
email_data = { 'name': 'Python Emailer' }
msg = MIMEMultipart('alternative')
msg['Subject'] = "The Email Subject"
msg['From'] = "\"Human Name\" <>"
msg['To'] = ""
html_email = email_template.render(email_data).encode('utf-8', 'replace')
part1 = MIMEText('Text content for the email (could be built with Jinja as well)', 'plain', 'utf-8')
part2 = MIMEText(html_email, 'html', 'utf-8')
#Assumes you have sendmail all set up
server = smtplib.SMTP('localhost')
server.sendmail(msg['From'], msg['To'], msg.as_string())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.