首页 > 解决方案 > 400 错误错误请求动态模板在 Sendgrid for Python 中不起作用

问题描述

问题

我正在尝试使用动态模板发送多封电子邮件,每封电子邮件使用 Mail Helper 类都有自己独特的替换。如果我不包含替换,那么代码可以完美运行并且邮件会被传递,但是一旦我包含替换,我就会收到“HTTP 错误 400:错误请求”。我正在使用虚拟环境并在我的 Flask 应用程序中运行它。我已经使用“pip install sendgrid”安装了 sendgrid,并将其更新到最新版本。

代码

to_emails = [
        To(
            email='person1@gmail.com',
            name='person1',
            substitutions={
                '-unsubscribeLink-':'https://www.example1.com'
            }
            ),
        To(
            email='person2@gmail.com',
            name='person2',
            substitutions={
                '-unsubscribeLink-':'https://www.example2.com'
            }
            ),
    ]

    message = Mail(
                from_email=From('support@website.com','Website'),
                to_emails=to_emails,
                is_multiple=True)

    message.template_id = 'd-c8d1a24b4539459b831407e2562045a9'
    try:
        sg = SendGridAPIClient('API KEY')
        response = sg.send(message)
        print(response.status_code)
        print(response.body)
        print(response.headers)
    except Exception as e:
        print(str(e))

例外

HTTP Error 400: Bad Request

技术细节

sendgrid-python 版本:我使用“pip install sendgrid”安装,它的版本是 6.3.1,所以我认为我没有使用“sendgrid-python”。蟒蛇版本:Python 3.6.7

我尝试升级,这就是它打印的内容:

pip install sendgrid --upgrade

Requirement already up-to-date: sendgrid in ./p37ve/lib/python3.6/site-packages (6.3.1)
Requirement already satisfied, skipping upgrade: python-http-client>=3.2.1 in ./p37ve/lib/python3.6/site-packages (from sendgrid) (3.2.7)

标签: pythonsendgridsendgrid-api-v3sendgrid-templatessendgrid-api-v2

解决方案


推荐阅读