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

5

I am a beginner in Python and Django and in the project I am 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 milestone and / or if there is any easier and / or better way.

    
asked by anonymous 30.01.2014 / 04:17

1 answer

6

I like to use EmailMultiAlternatives for the case of submissions with txt and html alternatives. If you want to use it one 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 django function, 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 for the submission to work, you'll need to set up a sending backend with the settings variable EMAIL_BACKEND. 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'
    
30.01.2014 / 04:35