如何使用 msg.send() 在 django 中的 html 电子邮件模板中传递用户名

how to pass username in html email template in django using msg.send()

我是 Django 编码的新手。我目前正在与 API 一起研究 DRF Django Rest Framework。我一直在尝试在用户注册后立即发送带有附件的 HTML 电子邮件模板。我已经实现了发送相同但我想将注册用户的电子邮件等动态内容从 views.py 传递到 HTML 电子邮件模板,但无法做到。我正在使用 msg.send().

输入VIEWS.PY:

def attachment(request):
   queryset = User.objects.all()
   em=[]
   h=[]
   for star in queryset.iterator():
       em.append(star.email)
   print(em)    
   h=em[-1]
   msg = mail.EmailMultiAlternatives(
        subject = 'attachment',
        body = 'Hi, Welcome!',
        from_email = 'anushstella97@gmail.com',
        to = [h],
        connection = con
        )
   msg.attach_file('C:/Users/hp/Downloads/APIV1-master/APIV1- 
     master/polls/img.jpg')
   msg_html = render_to_string('C:/Users/hp/Anaconda3/Lib/site- 
  packages/allauth/templates/account/email/email_confirmation_message.html' 
  , {"email": request.user.email})

   msg.send()
   return HttpResponse('<h1>Created</h1>')

在 HTML 模板中:

<p>Thanks for signing up! We're excited to have you as an early user.</p>
                <p> Your registered email is : </p>
                <p>
                    <strong> {{ email }} </strong></p>

要呈现模板,您可以使用 from django.template.loader 中的 render_to_string 并将上下文变量与其一起传递..

例如

from django.template.loader import render_to_string
html = render_to_string("account/email/email_confirmation_message.html", {"email": request.user.email})

里面 email_confirmation_message.html:

Hi {{ email }},
...