In python 3 and sendgrid I need to send BCC type emails and use a dynamic template, which I built
And here the HTML code of the place, Edit Module HTML:
CodePudding user response:
That is because you are trying to call the method add_personalization
on the to_emails
object, which is a list that you defined a few lines above:
to_emails = [To(email= '[email protected]']
You need to call add_personalization
to the message
object that you created, like this:
message.add_personalization(personalization)
Here's the full code with the fix:
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Attachment, Mail
from sendgrid.helpers.mail import Mail, From, To, Subject, PlainTextContent, HtmlContent, SendGridException, Personalization, Bcc
import os
API_KEY = "real id"
lista = { "sentences": ["Sentence 1 <br>", "Sentence 2 <br>"] }
recips = ['[email protected]', '[email protected]', '[email protected]']
to_emails = [To(email= '[email protected]']
personalization = Personalization()
personalization.add_to(To('[email protected]'))
for bcc_addr in recips:
personalization.add_bcc(Bcc(bcc_addr))
message = Mail(
from_email=('[email protected]'),
subject="email subject",
to_emails=to_emails,
is_multiple=True)
message.add_personalization(personalization)
message.dynamic_template_data = lista
message.template_id = 'real id'
try:
sendgrid_client = SendGridAPIClient(api_sendgrid)
response = sendgrid_client.send(message)
print(response.status_code)
#print(response.body)
#print(response.headers)
except Exception as e:
print(e.message)
return
Since your "sentences" dynamic template data is an array, you should likely loop through it too, so you can print each sentence. Try this in your template:
{{#each sentences}}
<div style="font-family: inherit; text-align: inherit">{{this}}</div>
{{/each}}