I have an email template that I use to send emails of different kinds. I'd rather not keep multiple email HTML templates, so the best way to handle this is to customize the message contents. Like so:
def email_form(request):
html_message = loader.render_to_string(
'register/email-template.html',
{
'hero': 'email_hero.png',
'message': 'We\'ll be contacting you shortly! If you have any questions, you can contact us at <a href="#">[email protected]</a>',
'from_email': '[email protected]',
}
)
email_subject = 'Thank you for your beeswax!'
to_list = '[email protected]'
send_mail(email_subject, 'message', 'from_email', [to_list], fail_silently=False, html_message=html_message)
return
When the email is sent however, the html codes don't work. The message appears as it is exactly, angled brackets and all. Is there a way for me to force it to render as HTML tags?
Adding a message To add a message, call: from django. contrib import messages messages. add_message(request, messages.INFO, 'Hello world.
Sending Emails with the Django ShellWe import the Django send_mail function. Then we import the settings object which contains all the global settings and the per-site settings (those inside the settings.py file). Finally, we pass all the needed arguments to the send_mail function.
The EMAIL_HOST_USER and EMAIL_HOST_PASSWORD settings, if set, are used to authenticate to the SMTP server, and the EMAIL_USE_TLS and EMAIL_USE_SSL settings control whether a secure connection is used.
Use EmailMessage to do it with less trouble:
First import EmailMessage
:
from django.core.mail import EmailMessage
Then use this code to send html email:
email_body = """\
<html>
<head></head>
<body>
<h2>%s</h2>
<p>%s</p>
<h5>%s</h5>
</body>
</html>
""" % (user, message, email)
email = EmailMessage('A new mail!', email_body, to=['[email protected]'])
email.content_subtype = "html" # this is the crucial part
email.send()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With