Skip to content

Instantly share code, notes, and snippets.

@frisi
Created May 18, 2016 23:39
Show Gist options
  • Save frisi/c0f3ea589bef166c3955fd76db47fbac to your computer and use it in GitHub Desktop.
Save frisi/c0f3ea589bef166c3955fd76db47fbac to your computer and use it in GitHub Desktop.
create html email out of zope template and compute txt version using
# for information how to use a zope page template to rende the html see
# https://github.com/collective/collective.dancing/blob/1.0.1/collective/dancing/composer.py#L342
from Products.CMFPlone.utils import safe_unicode
from email.Header import Header
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.Utils import formatdate
import email
import html2text
def create_html_mail(subject, html, text=None, from_addr=None, to_addr=None,
headers=None, encoding='UTF-8'):
"""Create a mime-message that will render HTML in popular
MUAs, text in better ones.
adapted collective.singing standard to strip style definitions off the
plain text version
"""
html = html.encode(encoding)
if text is None:
# Produce an approximate textual rendering of the HTML string,
# unless you have been given a better version as an argument
# see tests/test_newsletterformatter for configuration options
parser = html2text.HTML2Text()
# for images, simply show their alt-text
parser.ignore_images = False
parser.images_to_alt = True
# skip links to named anchors
parser.skip_internal_links = True
# if link text and href is the same, simply show link
parser.use_automatic_links = True
# protect links from linebreaks - looks good for emails
parser.protect_links = True
# true to show links next to their text content
parser.inline_links = True
text = parser.handle(safe_unicode(html))
else:
text = text.encode(encoding)
# if we would like to include images in future, there should
# probably be 'related' instead of 'mixed'
msg = MIMEMultipart('mixed')
# TODO: maybe later :)
# msg['From'] = Header("%s <%s>" % (send_from_name, send_from), encoding)
msg['Subject'] = Header(subject, encoding)
msg['From'] = from_addr
msg['To'] = to_addr
msg['Date'] = formatdate(localtime=True)
msg["Message-ID"] = email.Utils.make_msgid()
if headers:
for key, value in headers.items():
msg[key] = value
msg.preamble = 'This is a multi-part message in MIME format.'
alternatives = MIMEMultipart('alternative')
msg.attach(alternatives)
alternatives.attach(MIMEText(text, 'plain', _charset=encoding))
alternatives.attach(MIMEText(html, 'html', _charset=encoding))
return msg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment