'Django rest framework using Template to send an e-mail
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()
Solution 1:[1]
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 thehtml_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
'[email protected]',
['[email protected]'],
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
'[email protected]',
['[email protected]'],
)
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Carlos Osuna |