The django.core.mail.EmailMessage
class sends an email with the text/plain
content type, which is why the HTML tags appear. You can have two options:
- Use the
django.core.mail.send_mail
function indicating in the html_message
parameter the result of having rendered the template, something like this:
# quickly example of sending html mail
from django.core.mail import send_mail
from django.template.loader import get_template
# I preferred get_template(template).render(context) you can use render_to_string if you want
context = {'first_name': 'John', 'last_name': 'Devoe'}
template = get_template('my_custom_template.html').render(context)
send_mail(
'Custom Subject',
None, # Pass None because it's a HTML mail
'from@example.com',
['to@example.com'],
fail_silently=False,
html_message = template
)
- Use the
django.core.mail.EmailMultiAlternatives
class if you want to implement OOP. So the code will look like this:
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
# I preferred get_template(template).render(context) you can use render_to_string if you want
context = {'first_name': 'John', 'last_name': 'Devoe'}
template = get_template('my_custom_template.html').render(context)
msg = EmailMultiAlternatives(
'Custom Subject',
None, # This is the text context, just send None or Send a string message
'from@example.com',
['to@example.com'],
)
msg.attach_alternative(template, "text/html")
msg.send(fail_silently=False)
Finally, remember that sending via email will not access static files (for example the application's css) so I recommend using tools such as Postdrop that applies css styles to HTML online