python - 通过 sendgrid-python API 库将 django 对象上下文传递给 sendgrid 电子邮件
问题描述
我的 django 应用程序有一个视图,帐户可以使用 Sendgrid 的 API 向其联系人和订阅者发送时事通讯电子邮件。发送正在使用纯文本电子邮件:
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import (Mail, Subject, To, ReplyTo, SendAt, Content, From, CustomArg, Header)
def compose_email(request, send_to, *args, **kwargs):
...
if request.method == 'POST':
subject = request.POST.get('subject')
from_name = request.POST.get('from_name')
body = request.POST.get('body')
reply_to = request.POST.get('reply_to')
test_address = [request.POST.get('test_address')]
# send test email
if request.POST.get('do_test'):
if form.is_valid():
message = AccountEmailMessage(account=account, subject=subject,
from_name=from_name, destination=destination, body=body, reply_to=reply_to,
is_draft=True, is_sent=False)
message.save()
email = Mail(
subject=subject,
from_email=hi@app.foo,
html_content=body,
to_emails=test_address,
)
email.reply_to = ReplyTo(reply_to)
try:
sendgrid_client = SendGridAPIClient(settings.SENDGRID_API_KEY)
response = sendgrid_client.send(email)
message.sendgrid_id = response.headers['X-Message-Id']
message.save()
except Exception as e:
log.error(e)
messages.success(request, 'Test message has been successfully sent')
else:
messages.error(request, 'Please, check for errors')
这行得通。但我们想在来自 Account (account) 的 html 电子邮件模板中呈现 django 对象属性(通过模板标签的模型字段)[假设它只是account = Account.objects.get(id=selected_account)
视图中的 vanilla obj req 查询],我不清楚推荐的文档方法是什么.
尝试:
if request.method == 'POST':
subject = request.POST.get('subject')
from_name = request.POST.get('from_name')
body = request.POST.get('body')
reply_to = request.POST.get('reply_to')
if request.POST.get('send'):
if form.is_valid():
message = AccountEmailMessage(account=account, subject=subject,
from_name=from_name, destination=destination, body=body, reply_to=reply_to,
is_draft=False, is_sent=True)
message.save()
rendered = render_to_string('email/newsletter.html', {
'account': account,
'protocol': settings.DEFAULT_PROTOCOL,
'domain': settings.DOMAIN,
'message_body': body
})
email = Mail(
subject=subject,
from_email=hi@app.foo,
html_content=rendered,
to_emails=recipients,
mime_type='text/html'
)
email.reply_to = ReplyTo(reply_to)
try:
sendgrid_client = SendGridAPIClient(settings.SENDGRID_API_KEY)
response = sendgrid_client.send(email)
message.sendgrid_id = response.headers['X-Message-Id']
message.save()
except Exception as e:
log.error(e)
但是在提交时,这会引发错误:NoReverseMatch: Reverse for 'account' not found. 'account' is not a valid view function or pattern name
当我尝试将帐户作为 kwarg 传递给上下文并将其呈现为字符串时。
查看文档(https://github.com/sendgrid/sendgrid-python#use-cases)我看到 Mail() 有一个.dynamic_template_data
属性。处理来自同一个 obj 的大量字段以及图像 url 等属性的效率非常低,并且还需要使用旧的事务模板(https://sendgrid.com/docs/ui/sending-email/create- and-edit-legacy-transactional-templates/)。我看到 Sendgrid 有一个 Personalization obj ( https://sendgrid.com/docs/for-developers/sending-email/personalizations/ ) - 这是推荐的实现方式吗?
解决方案
感谢 Iain 在进一步的测试中意识到我们有两个问题:
试图通过 {% url %} 标签在模板中编码一个 url,这抛出了
NoReverseMatch
mime_type='text/html'
不是 Mail() 的有效 kwarg,也将其删除。
在 (1) 和 (2) 一切正常后,无需个性化
推荐阅读
- database - 在 PostgreSQL 上加密数据
- java - 方法太大:从 grails 2.3.7 升级到 grails 2.4.4 时
- ignite - Apache Ignite 胖客户端 - 轻量级
- reactjs - 在每个选项卡中使用 Auth 屏幕响应导航
- ios - iPhone应用程序可以进行负载测试吗?
- html - 如何垂直对齐内联元素和内联块元素
- perl - Perl PDL:搜索向量是在数组中还是在矩阵中
- java - 当var包含“.0”时如何将String转换为BigInteger
- json - Visual Studio Code 中的架构验证一次仅适用于第一个数组项
- clockify - 我无法使用 clockify API 获得“正在查找个人时间条目”