Search code examples
pythondjangodjango-templatesdjango-email

sending a safe html with django emailmessage


Good day, I'm trying to send a html in django email, pls what more can I added to the code. the email sending is functioning well but it still shows the html tags.

from celery import task
from django.template.loader import render_to_string, get_template
from django.core.mail import EmailMessage
from orders.models import Order


@task
def payment_completed(order_id):
    order = Order.objects.get(id=order_id)

    subject = f'Testing html sending'
    message = render_to_string('orders/order/pdf.html', {'order':order})
    email = EmailMessage(
        subject,
        message,
        '[email protected]',
        [order.email, '[email protected]']
    )
    email.content_subtype = 'html'
    email.send()

I've tried render_to_string and get_template same result

this is what i get in my mail.(showing HTML tags)


Solution

  • You can use EmailMultiAlternatives instead of EmailMessage, and code may look like this

    email = EmailMultiAlternatives(
        subject,
        message_plain_text,
        '[email protected]',
        [order.email, '[email protected]']
    )
    email.attach_alternative(message, 'text/html')
    email.send()