我是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>
答案 0 :(得分:0)
要渲染模板,您可以使用render_to_string
中的from django.template.loader
并将上下文变量与模板一起传递。
例如
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 }},
...