【问题标题】:how to pass username in html email template in django using msg.send()如何使用 msg.send() 在 django 的 html 电子邮件模板中传递用户名
【发布时间】:2019-07-18 03:25:03
【问题描述】:

我是 Django 编码的新手。我目前正在研究 DRF Django Rest Framework 以及 API。我一直在尝试在用户注册后立即发送带有附件的 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>

【问题讨论】:

  • 会发生什么,h 是否获得预期值?我可以在那里看到一个错误,您将 context 而不是 content 传递给 attach_alternative
  • h 获取电子邮件要发送到的电子邮件字符串。我想通过同样的。我将上下文更改为内容,但它仍然相同。
  • 好的,有什么问题吗?您只需将要填充电子邮件模板的任何内容添加到上下文字典中即可。如果“注册用户的电子邮件”是指提出请求的用户,您可以这样做request.user.email
  • 我的html代码好吗?
  • 如果您想让它这么说并显示定义为h的电子邮件地址

标签: django django-rest-framework django-views django-allauth django-rest-framework-jwt


【解决方案1】:

要渲染模板,您可以使用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 }},
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-16
    • 2015-05-29
    • 1970-01-01
    • 2018-10-30
    • 2011-02-18
    • 2020-09-08
    • 1970-01-01
    相关资源
    最近更新 更多