[Django]-Django 1.7: how to send emails by using an html/css file as template

3👍

With include:

<html lang="en">
 <head>
  <link href="path/to/application.css" rel="stylesheet">
 </head>
 <body>
  <div class="email_header">
    [..]
    <a href="http://mysite.it"><img src="images/logo.png"/></a>
  </div>
  <div class="email_body">
   [..]
   {% include "my_message.txt" %}
  </div>
 </body>

1👍

When you write a HTML template for emails, you should consider write your style inline:

<div style="display: none;"></div>

Because some email clients won’t display your styles as you expect. BTW, let’s suppose you have a template styled in the convenient way.

<html lang="en">
 <head>
  <link href="path/to/application.css" rel="stylesheet">
 </head>
 <body>
  <div class="email_header">
    [..]
    <a href="http://mysite.it"><img src="images/logo.png"/></a>
  </div>
  <div class="email_body">
   [..]
   Dear {{ name }}
   You won {{ money }}

   {# Or you could use include #}
  </div>
 </body>

I will assume that you’ve configured a directory for your templates, and it’s working well. To send an HTML template with a context you could do this:

from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context

class Email():

    @staticmethod
    def send_html_email(*args, **kwargs):
        from_email = kwargs.get('from_email', 'default@email.from')
        context = Context(kwargs.get('context'))
        template = get_template(kwargs.get('template_name'))
        body = template.render(context)
        subject = kwargs.get('subject', 'Default subject here')
        headers = kwargs.get('headers', {})

        message = EmailMultiAlternatives(
                subject,
                from_email,
                kwargs.get('to'),
                headers=headers
            )

        message.attach_alternative(body, 'text/html')
        message.send(fail_silently=False)

Then, when you want to send an email you use the send_html_email method:

# views.py
...
data = {
          'from_email': 'my_email@whatever.com',
          'subject': 'My pretty subject',
          'to': ['recipient@email.com', ],
          'template_name': 'templates_dir/my_html_message.html',
          'context': {'name': 'Name of user', 'money': 1000},
        }

Email.send_html_email(**data)
...
👤Gocht

Leave a comment