繁体   English   中英

在 sendgrid 中发送多个动态模板电子邮件时出现个性化字段错误

[英]Personalizations field error when sending multiple dynamic template emails in sendgrid

我正在尝试使用 Django 中的 Sendgrid 动态模板发送批量 email 并收到此错误: 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

output 是

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 class 在使用初始值初始化期间做了一些事情(它根据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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM