What is the best way to email with HTML in Django?

Asked

Viewed 2,008 times

6

I’m a beginner in Python and Django and in the project I’m doing for study, I send an email, which has an HTML template. I was able to send an HTML email using EmailMessage:

msg = EmailMessage(subject, template.render(variables), sender, recipients)
msg.content_subtype = "html"
msg.send()

I would like to know if this is the recommended line and/or if there is any easier and/or better way.

1 answer

7


I like to use Emailmultialternatives for sending with txt and html alternatives. If you want to use it a way to do it is:

from django.template.loader import render_to_string
from django.core.mail import EmailMultiAlternatives

message_html = render_to_string('seutemplate.html', dict_contexto)
message_txt = render_to_string('seutemplate.txt', dict_contexto)

subject = u"Um assunto"
from_email = u'[email protected]'
msg = EmailMultiAlternatives(subject, message_txt, from_email,        
                             ['[email protected]'])
msg = msg.attach_alternative(message, "text/html")
msg.send()

Or if you want something simpler, you can choose the default function of Django, the send_mail. Example:

from django.core.mail import send_mail

send_mail('Subject here', 'Here is the message.', '[email protected]',
          ['[email protected]'], fail_silently=False)

Remembering that in order for the upload to work, you will need to configure an upload backend, with the EMAIL_BACKEND variable from Settings. To test location you can use the backend console, where the message, after sending, will appear in the shell. To use the backend console assign the following value to the EMAIL_BACKEND:

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

Browser other questions tagged

You are not signed in. Login or sign up in order to post.