Search code examples
pythonemailsendgridbccpersonalization

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?


Solution

  • 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.