Search code examples
pythonhtmlcssdjangohtml-email

Django how to send html-designed email bodies


On my Django project I am trying to send beautiful mails with colorful body and so on. My mail body constructing function looks like the following:

def construct_mail_body():
    user = User.objects.get(id=1)
    context = {
        'username': user.username,
    }
    template = render_to_string('mail/mail_body.html', context=context)
    message = strip_tags(template)
    return message

mail_body.html:

{% load static %}

<h3>Hello <span style="color: red;">{{ username }}</span>,</h3>

<h3>You've successfully completed our Tutorial!></h3>

<h3>Congratulations!</h3>

But it doesn't work as expected. My mail bodies looks like:

Body 1:

Body

Body 2 (Btw, why this happens? Why the mail is in purple?):

Body #2

So how to make HTML tags work properly and is it possible to add some styling properties of css? Thanks!

Solved:

I found a way how to do that:

from django.core.mail import EmailMessage


mail = EmailMessage(
        subject,
        body,
        settings.EMAIL_HOST_USER,
        [email],
    )
mail.fail_silently = False
mail.content_subtype = 'html'
mail.send()

This way it works properly.


Solution

  • This is possible, but stick to hex colours, e.g. #ff0000, instead of a named colour.

    Text can all go purple, as Willem commented, when something is repeated, or for replies. If you change the subject line when testing, it won't group them, and so it won't do this.

    Keep using inline CSS, but stick to HTML4 and CSS2 (higher can be achieved but as a progressive enhancement for some email clients only).