Bob
Bob

Reputation: 329

Django email message as HTML

I have an email template that I use to send emails of different kinds. I'd rather not keep multiple email HTML templates, so the best way to handle this is to customize the message contents. Like so:

def email_form(request):
    html_message = loader.render_to_string(
            'register/email-template.html',
            {
                'hero': 'email_hero.png',
                'message': 'We\'ll be contacting you shortly! If you have any questions, you can contact us at <a href="#">[email protected]</a>',
                'from_email': '[email protected]',
            }
        )
    email_subject = 'Thank you for your beeswax!'
    to_list = '[email protected]'
    send_mail(email_subject, 'message', 'from_email', [to_list], fail_silently=False, html_message=html_message)
    return

When the email is sent however, the html codes don't work. The message appears as it is exactly, angled brackets and all. Is there a way for me to force it to render as HTML tags?

Upvotes: 8

Views: 16578

Answers (3)

Ghasem
Ghasem

Reputation: 15573

Use EmailMessage to do it with less trouble:

First import EmailMessage:

from django.core.mail import EmailMessage

Then use this code to send html email:

email_body = """\
    <html>
      <head></head>
      <body>
        <h2>%s</h2>
        <p>%s</p>
        <h5>%s</h5>
      </body>
    </html>
    """ % (user, message, email)
email = EmailMessage('A new mail!', email_body, to=['[email protected]'])
email.content_subtype = "html" # this is the crucial part 
email.send()

Upvotes: 36

Bob
Bob

Reputation: 329

Solved it. Not very elegant, but it does work. In case anyone's curious, the variable placed in the email template should be implemented as so:

{{ your_variable|safe|escape }}

Then it works! Thanks guys!

Upvotes: 4

binu.py
binu.py

Reputation: 1216

You can use EmailMultiAlternatives feature present in django instead of sending mail using send mail. Your code should look like the below snipet.

from django.core.mail import EmailMultiAlternatives

def email_form(request):
    html_message = loader.render_to_string(
            'register/email-template.html',
            {
                'hero': 'email_hero.png',
                'message': 'We\'ll be contacting you shortly! If you have any questions, you can contact us at <a href="#">[email protected]</a>',
                'from_email': '[email protected]',
            }
        )
    email_subject = 'Thank you for your beeswax!'
    to_list = '[email protected]'
    mail = EmailMultiAlternatives(
            email_subject, 'This is message', 'from_email',  [to_list])
    mail.attach_alternative(html_message, "text/html")
    try:
        mail.send()
    except:
        logger.error("Unable to send mail.")

Upvotes: 5

Related Questions