How to send html email with django with dynamic content in it?

后端 未结 7 1148
一向
一向 2020-12-04 11:09

Can anyone please help me sending html email with dynamic contents. One way is to copy the entire html code into a variable and populate the dynamic code within it in Django

7条回答
  •  半阙折子戏
    2020-12-04 11:24

    Django includes the django.core.mail.send_mail method these days (2018), no need to use EmailMultiAlternatives class directly. Do this instead:

    from django.core import mail
    from django.template.loader import render_to_string
    from django.utils.html import strip_tags
    
    subject = 'Subject'
    html_message = render_to_string('mail_template.html', {'context': 'values'})
    plain_message = strip_tags(html_message)
    from_email = 'From '
    to = 'to@example.com'
    
    mail.send_mail(subject, plain_message, from_email, [to], html_message=html_message)
    

    This will send an email which is visible in both html-capable browsers and will show plain text in crippled email viewers.

提交回复
热议问题