我试图在Django中使用Sendgrid动态模板发送一封批量邮箱,但收到了以下错误:The personalizations field is required and must have at least one personalization.

使用sendgrid 6.9.7

有人知道我可能会出什么问题吗:

from django.conf import settings
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail, To

def send_mass_email():

    to_emails = [
        To(email='email1@gmail.com',
           dynamic_template_data={
              "thing_i_want_personalized": 'hello email 1',
           }),
        To(email='email2@gmail.com',
           dynamic_template_data={
              "thing_i_want_personalized": 'hello email 2',
           }),
    ]

    msg = Mail(
      from_email='notifications@mysite.com>',
    )
    msg.to_emails = to_emails
    msg.is_multiple = True
    msg.template_id = "d-template_id"

    try:
        sendgrid_client = SendGridAPIClient(settings.SENDGRID_API_KEY)
        response = sendgrid_client.send(msg)
        print(response.status_code)
        print(response.body)
        print(response.headers)
    except Exception as e:
        print(e)
        print(e.body)

    return

输出是

HTTP Error 400: Bad Request
b'{"errors":[{"message":"The personalizations field is required and must have at least one personalization.","field":"personalizations","help":"http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#-Personalizations-Errors"}]}'

推荐答案

Mail类在初始化过程中使用初始值做一些事情(它根据to_emails设置私有内部值),因此需要在初始化器中传递to_emailsis_multiple,而不是更晚:

from django.conf import settings
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail, To

def send_mass_email():
    to_emails = [
        To(email='email1@gmail.com',
           dynamic_template_data={
              "thing_i_want_personalized": 'hello email 1',
           }),
        To(email='email2@gmail.com',
           dynamic_template_data={
              "thing_i_want_personalized": 'hello email 2',
           }),
    ]

    msg = Mail(
      from_email='notifications@mysite.com>',
      to_emails = to_emails,
      is_multiple = True
    )
    msg.template_id = "d-template_id"

    try:
        sendgrid_client = SendGridAPIClient(settings.SENDGRID_API_KEY)
        response = sendgrid_client.send(msg)
        print(response.status_code)
        print(response.body)
        print(response.headers)
    except Exception as e:
        print(e)
        print(e.body)

    return

Python相关问答推荐

在应用循环中间保存pandas DataFrame

优化在numpy数组中非零值周围创建缓冲区的函数的性能

Chatgpt API不断返回错误:404未能从API获取响应

多处理代码在while循环中不工作

使用miniconda创建环境的问题

从numpy数组和参数创建收件箱

如何使用根据其他值相似的列从列表中获取的中间值填充空NaN数据

计算组中唯一值的数量

Python+线程\TrocessPoolExecutor

在ubuntu上安装dlib时出错

如何并行化/加速并行numba代码?

使用BeautifulSoup抓取所有链接

Cython无法识别Numpy类型

如何在PythonPandas 中对同一个浮动列进行逐行划分?

Seaborn散点图使用多个不同的标记而不是点

当我定义一个继承的类时,我可以避免使用`metaclass=`吗?

如何从数据框列中提取特定部分并将该值填充到其他列中?

从列表中分离数据的最佳方式

如何在python tkinter中绑定键盘上的另一个回车?

在MongoDB文档中仅返回数组字段