Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With sendgrid and python, how to send an email to multiple BCC at once?

Please, in python3 and sendgrid I need to send an email to multiple addresses in BCC way. I have these emails on a list. I'm trying like this with Personalization:

import os
import json
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail, Personalization, From, To, Cc, Bcc

recips = ['[email protected]', '[email protected]', '[email protected]']

new_email = Mail(from_email='[email protected]', 
              to_emails = '[email protected]',
              subject= "email subject", 
              html_content="Hi<br><br>This is a test")

personalization = Personalization()
for bcc_addr in recips:
    personalization.add_bcc(Bcc(bcc_addr))

new_email.add_personalization(personalization)

try:
    sg = SendGridAPIClient('API_KEY')
    response = sg.send(new_email)
    print(response.status_code)
    print(response.body)
    print(response.headers)
except Exception as e:
    print(e.to_dict)

In a test with real email addresses an error appears: HTTP Error 400: Bad Request, with dictionary: {'errors': [{'message': 'The to array is required for all personalization objects, and must have at least one email object with a valid email address.', 'field': 'personalizations.0.to', 'help': 'http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.personalizations.to'}]}

Please does anyone know why?

like image 422
Reinaldo Chaves Avatar asked Oct 26 '25 21:10

Reinaldo Chaves


1 Answers

Twilio SendGrid developer evangelist here.

When adding multiple bccs to your personalization object, you need to loop through the email addresses and add them each individually.

import os
import json
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail, Personalization, Bcc, To

recips = ['[email protected]', '[email protected]', '[email protected]']

new_email = Mail(
  from_email='[email protected]', 
  subject= "email subject", 
  html_content="Hi<br><br>This is a test"
)

personalization = Personalization()

personalization.add_to(To('[email protected]'))

for bcc_addr in recips:
    personalization.add_bcc(Bcc(bcc_addr))

new_email.add_personalization(personalization)

try:
    sg = SendGridAPIClient('API_KEY')
    response = sg.send(new_email)
    print(response.status_code)
    print(response.body)
    print(response.headers)
except Exception as e:
    print(e.to_dict)

Check out this mail example for how to use the various parts of personalizations.

like image 87
philnash Avatar answered Oct 28 '25 10:10

philnash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!