Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python HTML Email Sender
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
</head>
<body style="text-align:center">
<table width="600" style="margin:0 auto; text-align: left">
<tr>
<td>
<h1>Python HTML Emailer</h1>
</td>
</tr>
<tr>
<td>
Hello, {{name}}
</td>
</tr>
</table>
</body>
</html>
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(tfile.read().decode('utf-8', 'replace'))
email_data = { 'name': 'Python Emailer' }
msg = MIMEMultipart('alternative')
msg['Subject'] = "The Email Subject"
msg['From'] = "\"Human Name\" <email@address.com>"
msg['To'] = "to_address@whatever.com"
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')
msg.attach(part1)
msg.attach(part2)
#Assumes you have sendmail all set up
server = smtplib.SMTP('localhost')
server.sendmail(msg['From'], msg['To'], msg.as_string())
server.quit()
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.