Email body is showing html code in place of template in django

Viewed 247

I am sending email using smtp in django but its showing its HTML code.
Here is my django view and template

view.py

current_site = get_current_site(request)
mail_subject = 'Activate Your Account'
mail_message = render_to_string('mail_body.html', {
    'user' : user,
    'domain' : current_site.domain,
    'uid' : urlsafe_base64_encode(force_bytes(user.pk)),
    'token' : default_token_generator.make_token(user)
})

mail_to = email,
email = EmailMessage( mail_subject, mail_message, to = mail_to )
email.send()

mail_body.html

<div>
{% autoescape off %}
<b class="text-center">Hello {{ user.username }}</b><br>
Please click on the link below to verify your email address and complete your registration.

<a class="btn btn-primary btn-block" href="http://{{ domain }}{% url 'auth' uidb64=uid token=token 
%}" role="button" target="_blank">Verify</a>
<hr />
<br />
If you think, it's not you, then just ignore this email. 
{% endautoescape %} 
</div>
3 Answers

As per the documentation: https://docs.djangoproject.com/en/3.1/topics/email/

You can use the function send_mail as a wrapper to the EmailMessage object and the send_mail function allow you to set html_message:

from django.core.mail import send_mail
send_mail(mail_subject, '', 'you@example.com', [mail_to], html_message=mail_message)

This is because you use the second parameter in the EmailMessage. This is the email message as text, not HTML.

You can use the html_message=… parameter [Django-doc] to specify the message in HTML. You will still need a value for the second parameter, this is normally an email but in raw text:

mail_to = email,
raw_text = '… email, but then in raw text without makeup …'
email = EmailMessage(mail_subject, raw_text, to=mail_to, html_message=mail_message)
email.send()

email.content_subtype='html' just use that and your problem will likely be solved

Related