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

后端 未结 7 1151
一向
一向 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:15

    Example:

    from django.core.mail import EmailMultiAlternatives
    from django.template.loader import render_to_string
    from django.utils.html import strip_tags
    
    subject, from_email, to = 'Subject', 'from@xxx.com', 'to@xxx.com'
    
    html_content = render_to_string('mail_template.html', {'varname':'value'}) # render with dynamic value
    text_content = strip_tags(html_content) # Strip the html tag. So people can see the pure text at least.
    
    # create the email, and attach the HTML version as well.
    msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
    msg.attach_alternative(html_content, "text/html")
    msg.send()
    

提交回复
热议问题