400错误错误错误请求动态模板,替换在Sendgrid for Python中不起作用

2024-05-16 10:29:39 发布

您现在位置: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版本: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)

Tags: installpipto代码版本comhttpmessage