1

I want to send a styled email using HTML tags. The mail is sent successfully but without style and the HTML tags are presented as a text in the email.

handles.py

@receiver(order_created)
def on_order_created(sender, **kwargs):
    order=kwargs['order']
    capture_email= order.customer.user.email
    name= order.customer.user.username
    title= 'Thank you ' + name
    order_items=OrderItem.objects.filter(order=order)

    template= render_to_string('index.html',{'order_items':order_items,'name':name})
    # text_content = strip_tags(template)

    email =EmailMessage(
        title,
        template,
        settings.EMAIL_HOST_USER,
        [capture_email],
        
    )    
    email.fail_silently=False,
    email.send()
Anaghim
  • 11
  • 2

1 Answers1

2

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:

  1. 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
)

  1. 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

Carlos Osuna
  • 167
  • 2