I'm trying to send a bulk email using Sendgrid Dynamic Templates in Django and getting this error: The personalizations field is required and must have at least one personalization.
Using sendgrid 6.9.7
Does anyone see where I might be going wrong:
from django.conf import settings
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail, To
def send_mass_email():
to_emails = [
To(email='[email protected]',
dynamic_template_data={
"thing_i_want_personalized": 'hello email 1',
}),
To(email='[email protected]',
dynamic_template_data={
"thing_i_want_personalized": 'hello email 2',
}),
]
msg = Mail(
from_email='[email protected]>',
)
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
The output is
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"}]}'
CodePudding user response:
The Mail
class does some stuff during initialization with the initial values (it sets private internal values based on to_emails
), so you need to pass to_emails
and is_multiple
in the initializer and not later:
from django.conf import settings
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail, To
def send_mass_email():
to_emails = [
To(email='[email protected]',
dynamic_template_data={
"thing_i_want_personalized": 'hello email 1',
}),
To(email='[email protected]',
dynamic_template_data={
"thing_i_want_personalized": 'hello email 2',
}),
]
msg = Mail(
from_email='[email protected]>',
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