python - 通过 sendgrid-python API lib 将 django 对象上下文传递给 sendgrid 电子邮件

标签 python django python-3.x sendgrid sendgrid-api-v3

我的 django 应用程序有一个 View ,帐户可以使用 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 对象属性(通过模板标签的模型字段)[假设它只是一个普通的 obj req 查询 account = Account.objects.get(id=selected_account) 在 View 中],我不清楚推荐的文档方法是什么。

尝试:

    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:未找到“帐户”的反向。当我尝试将帐户作为 kwarg 传递到上下文并将其呈现为字符串时,“帐户”不是有效的 View 函数或模式名称

查看文档 ( 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 有一个个性化对象 ( https://sendgrid.com/docs/for-developers/sending-email/personalizations/ ) - 这是实现此功能的推荐方法吗?

最佳答案

感谢 Iain 的进一步测试,我们发现我们有两个问题:

  1. 尝试通过 {% url %} 标记对模板中的 url 进行编码,这引发了 NoReverseMatch

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

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

关于python - 通过 sendgrid-python API lib 将 django 对象上下文传递给 sendgrid 电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59524405/

相关文章:

python - 在 JSONField 中搜索文本

javascript - Python Pandas read_excel 和 to_json 日期格式错误

javascript - 如何在 Django 中创建动态表单集?

python - Django TypeError at/sitemap.xml 序列索引必须是整数,而不是 'slice'

python - 是否可以阻止 python 终止直到 block 结束?

python - 字节类型的 UnicodeDecodeError

Python 中 Java 的 Mahout 等价物

python - Selenium+python 报告

python - 使用 structlog 设置日志级别

Docker 上的 Django 不安装 mysqlclient