简体   繁体   中英

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 = ['email1@gmail.com', 'email2@gmail.com', 'email2@gmail.com']

new_email = Mail(from_email='emailsender@gmail.com', 
              to_emails = 'one_valid_email@gmail.com',
              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?

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 = ['email1@gmail.com', 'email2@gmail.com', 'email2@gmail.com']

new_email = Mail(
  from_email='emailsender@gmail.com', 
  subject= "email subject", 
  html_content="Hi<br><br>This is a test"
)

personalization = Personalization()

personalization.add_to(To('emailsender@gmail.com'))

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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