【发布时间】:2014-09-22 19:50:50
【问题描述】:
我想向某个地址发送 html 电子邮件。
这是我的代码的一部分:
views.py
def addNewEvent(request):
try:
eventStatus = EventStatus.objects.filter(event=request.GET["id"])[0]
#try to send the mail
html = get_template('mail.html')
d = Context({ 'username': usuario.name,'title':'Testing mail!!','eventStatusId': str(eventStatus.id)})
html_content = html.render(d)
msg = EmailMultiAlternatives('Testing yo','Skyforger!', 'mymail@gmail.com', [mail2@gmail.com])
msg.attach_alternative(html_content, "text/html")
msg.send()
print('EventStatus id '+str(eventStatus.id))
except Exception, e:
print ('the error %s',(str(e)))
response = getBaseJSON()
response["event_id"]= eventStatus.id
return HttpResponse(json.dumps(response), content_type="application/json")
mail.html
<html>
<body>
<h1>{{title}}</h1>
<h2>Hi {{username}}</h2>
<h3>Message to friend</h3>
<form action="http://localhost:8000/confirmEvent" method="POST">
{% csrf_token %}
<input type="hidden" name="id" value="{{eventStatusId}}">
<textarea name="message_to_friend"></textarea><br>
<input type="submit" value="I'LL BE THERE!!">
</form>
</body>
</html>
邮件发送正常,但提交表单时,显示此错误:
禁止 (403) CSRF 验证失败。请求中止。
我找不到解决该错误的方法。
我关注了很多这样的答案:
https://stackoverflow.com/a/10388110
Forbidden (403) CSRF verification failed. Request aborted. Even using the {% csrf_token %}
没有成功。
如何在 html 邮件中发送表单以避免 CSRF 错误。
【问题讨论】:
-
我看到您已经看到了答案,但我没有在您的表单中看到
{% csrf_token %} -
需要明确的是,mail.html 是否呈现并发送给在邮件客户端中打开它的用户? CSRF 令牌对应于 当前用户,而不是将在邮件中打开它的用户。此外,由于您使用 Context() 来呈现表单,因此很可能不包含 CSRF 令牌。您应该使用 RequestContext:docs.djangoproject.com/en/dev/ref/contrib/csrf
-
@mgnb 在我的情况下我应该如何使用 RequestContext ?我读到它必须用作 render_to_response 中的参数,但我没有使用该方法
标签: django django-views csrf django-csrf