“dict”对象没有属性“encode”Django邮件

2024-04-28 16:04:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在表单提交后使用django-mail-templated发送电子邮件。在

当我提交我的表格时,我得到了这个错误:

'dict' object has no attribute 'encode'

设置.py

EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'example@gmail.com'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_PORT = 587

视图.py

^{pr2}$

机票

{% extends "mail_templated/base.tpl" %}

{% block subject %}
Hello {{ user }}
{% endblock %}

{% block body %}
{{ user }}, this is a plain text message.
{% endblock %}

{% block html %}
{{ user }}, this is an <strong>html</strong> message.
{% endblock %}

如您所见,我使用django邮件模板作为文档,那么为什么会出现此错误?在


Tags: djangopycomhostmessageisemail错误
2条回答

由于某些原因,您假设send_mail将使用您提供的上下文呈现模板;但是它不知道模板的任何信息,它期望的是一个包含电子邮件正文的字符串。您需要单独渲染并将其传递给函数:

from django.template.loader import render_to_string
body = render_to_string('autres/ticket_m.tpl', {'user': request.user})
send_mail(
    'Subject',
    body, 
    'example@gmail.com ', 
    ['example@domain.ch']
)

请注意,第一个参数是电子邮件的主题。在

^{}的签名与您假定的签名不同。第一个参数是主题,第二个参数是已经呈现的消息,两者都是字符串:

send_mail(
    'subject of your email', 
    render_to_string('autres/ticket_m.tpl', {'user': request.user}),
    'example@gmail.com ', 
    ['example@domain.ch']
)

必需参数,如documentation

  • subject: A string.
  • message: A string.
  • from_email: A string.
  • recipient_list: A list of strings, each an email address. Each member of recipient_list will see the other recipients in the “To:” field of the email message.

相关问题 更多 >