Skip to content

Instantly share code, notes, and snippets.

@whusterj
Last active August 29, 2015 14:09
Show Gist options
  • Save whusterj/1cb3a25bd5afed57a902 to your computer and use it in GitHub Desktop.
Save whusterj/1cb3a25bd5afed57a902 to your computer and use it in GitHub Desktop.
"""
An example of how to use html2text to create plaintext emails without all the headache.
"""
import html2text
from django.conf import settings
from django.core.mail.message import EmailMultiAlternatives
from django.template.loader import render_to_string
ORDER_NOTIFY_TEMPLATE = 'staff_order_notification.html'
def notify_staff_about_new_order(new_order):
subject = '{} Submitted a New Order'.format(new_order.user)
# Render the HTML template
body_html = render_to_string(
ORDER_NOTIFY_TEMPLATE,
{'order': new_order},
)
# Take rendered HTML and convert to plain text (Markdown)
body_plaintext = html2text.html2text(body_html)
email_staff(subject, body_html, body_plaintext)
def email_staff(subject, body_html, body_plaintext):
"""Emails the configured STAFF_EMAIL_ADDRESS"""
send_to = [settings.STAFF_EMAIL_ADDRESS]
send_from = settings.DEFAULT_FROM_EMAIL
# Put the email together, using plaintext by default
email = EmailMultiAlternatives(
subject,
body_plaintext,
send_from,
send_to,
)
# Then attach the HTML version (most clients will prefer this by default)
email.attach_alternative(body_html, "text/html")
# email away!
email.send(fail_silently=False)
<!-- Stupid-simple Django HTML template, for example -->
<h1>New Order from {{ order.user }}!</h1>
<p><em>Here are the down 'n dirty deets on this order!</em></h1>
<p>
User: {{ order.user }}<br>
Order #: {{ order.id }}
</p>
<table>
<tr>
<td>Item</td>
<td>SKU</td>
<td>Price</td>
</tr>
<tr>
<td>{{ order.item.name }}</td>
<td>{{ order.item.sku }}</td>
<td>{{ order.item.price }}</td>
</tr>
<tr>
<td>{{ order.item.name }}</td>
<td>{{ order.item.sku }}</td>
<td>{{ order.item.price }}</td>
</tr>
<tr>
<td></td>
<td>Taxes:</td>
<td>{{ order.taxes }}</td>
</tr>
<tr>
<td></td>
<td>Subtotal:</td>
<td>{{ order.subtotal }}</td>
</tr>
</table>
# New Order from {{ order.user }}!
_Here are the down 'n dirty deets on this order!_
User: {{ order.user }}
Order #: {{ order.id }}
|Item | SKU | Price |
|-----------------------|----------------------|------------------------|
| {{ order.item.name }} | {{ order.item.sku }} | {{ order.item.price }} |
| {{ order.item.name }} | {{ order.item.sku }} | {{ order.item.price }} |
| | Taxes: | {{ order.taxes }} |
| | Subtotal: | {{ order.subtotal }} |
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment