Django: send templated email with text and html

File with text template

# file mail_order.txt

Hello, dear {{ user_name }}!

You ordered ...

---
Best regards, SuperShop!

File with html template

# file mail_order.html

<!DOCTYPE html>
<html>
<head>
<style>
...
</style>

</head>
<body>

<h3>Hello, dear {{ user_name }}!</h3>

You ordered 

<table>
...
</table>

---
<strong>Best regards, SuperShop!</strong>

</body>
</html>

File with view

from django.views.generic.edit import FormView
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string

class OrderView(FormView):
    form_class = OrderForm
    template_name = "basket/order_form.html"

    def get_initial(self):
        init = {'agree': True}
        return init

    def get_success_url(self):
        return reverse('basket:thanks')

    def get_context_data(self, **kwargs):
        context = super(OrderView, self).get_context_data(**kwargs)
        ...
        return context

    def form_valid(self, form):
        order = form.save()

        subject, from_email, to = BASKET_MAIL_SUBJECT, BASKET_MAIL_FROM, BASKET_MAIL_TO
        ctx = {'order': order}
        text_content = render_to_string('basket/mail_order.txt', ctx).encode("utf-8")
        html_content = render_to_string('basket/mail_order.html', ctx).encode("utf-8")
        subject = subject % order.amount
        msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
        msg.attach_alternative(html_content, "text/html")
        msg.send()

        return redirect(self.get_success_url())
comments powered by Disqus