在 send_email() 中使用变量

Use variables in send_email()

我在一封电子邮件中使用 html 作为消息并传递一些变量,如下所示:

subject = 'Some Subject'
plain = render_to_string('templates/email/message.txt',{'name':variableWithSomeValue,'email':otherVariable})
html = render_to_string('templates/email/message.html',{'name':variableWithSomeValue,'email':otherVariable})
from_email = setting.EMAIL_HOST_USER
send_email(subject, plain, from_email, [variableToEmail], fail_silently=False, html_message=html)

效果很好,但现在我需要从数据库中的一个 table 中获取消息内容,table 有三列,在第一个寄存器中的每一列中都有这个值。 subject 列有 Account Infoplain 列有 Hello {{name}}. Now you can access to the site using this email address {{email}}.html 列有 <p>Hello <strong>{{name}}</strong>.</p> <p>Now you can access to the site using this email address <strong>email</strong>.</p>.

因此,为了从数据库中获取值,我这样做 obj = ModelTable.objects.get(id=1) 然后这样做:

subject = obj.subject
plain = (obj.plain,{'name':variableWithSomeValue,'email':otherVariable})
html = (obj.html,{'name':variableWithSomeValue,'email':otherVariable})
from_email = setting.EMAIL_HOST_USER
send_email(subject, plain, from_email, [variableToEmail], fail_silently=False, html_message=html)

但这给了我错误

AttributeError: 'tuple' object has no attribute 'encode'

所以我尝试传递 .encode(´utf-8´) 作为值并给了我同样的错误,然后更改每个变量的值并发现问题来自 plain = (obj.plain,{'name':variableWithSomeValue,'email':otherVariable})html = (obj.html,{'name':variableWithSomeValue,'email':otherVariable})所以我认为我以错误的方式传递了变量,所以 我怎样才能以正确的方式做到这一点? 或者可能是为了数据库的编码,但我认为使用 .encode(utf-8) 应该可以解决这个问题,但我真的认为我以错误的方式传递了变量 nameemail

抱歉冗长 post 和我的语法错误,如果需要更多信息,请告诉我。

我假设 obj.plain 和 obj.html 是代表您的模板的字符串(存储在数据库中)?

如果是这样,那么您仍然需要呈现您的电子邮件内容。但是,不是使用将模板路径作为第一个参数的 render_to_string,而是要基于字符串创建模板,然后呈现该模板。考虑如下内容:

...
from django.template import Context, Template
plain_template = Template(obj.plain)
context = Context({'name':variableWithSomeValue,'email':otherVariable})
email_context = plain_template.render(context)
...
send_email(...)

这里有一个 link 可以更好地解释渲染字符串模板,而不是渲染模板文件。

https://docs.djangoproject.com/en/1.7/ref/templates/api/#rendering-a-context