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

后端 未结 7 1143
一向
一向 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:32

    This should do what you want:

    from django.core.mail import EmailMessage
    from django.template import Context
    from django.template.loader import get_template
    
    
    template = get_template('myapp/email.html')
    context = Context({'user': user, 'other_info': info})
    content = template.render(context)
    if not user.email:
        raise BadHeaderError('No email address given for {0}'.format(user))
    msg = EmailMessage(subject, content, from, to=[user.email,])
    msg.send()
    

    See the django mail docs for more.

提交回复
热议问题