首页 > 解决方案 > 通过 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/ ) - 这是推荐的实现方式吗?

标签: pythondjangopython-3.xsendgridsendgrid-api-v3

解决方案


感谢 Iain 在进一步的测试中意识到我们有两个问题:

  1. 试图通过 {% url %} 标签在模板中编码一个 url,这抛出了NoReverseMatch

  2. mime_type='text/html'不是 Mail() 的有效 kwarg,也将其删除。

在 (1) 和 (2) 一切正常后,无需个性化


推荐阅读