使用sendgrid和python,如何一次向多个BCC发送电子邮件?

Rei*_*ves 2 python email bcc personalization sendgrid

请,在 python3 和 sendgrid 中,我需要以密件抄送的方式向多个地址发送电子邮件。我将这些电子邮件列在一个列表中。我正在尝试这样的个性化:

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)
Run Code Online (Sandbox Code Playgroud)

在使用真实电子邮件地址的测试中,出现错误: HTTP 错误 400:错误请求,带有字典:{'errors': [{'message': '所有个性化对象都需要 to 数组,并且必须至少有一封电子邮件具有有效电子邮件地址的对象。', 'field': 'personalizations.0.to', 'help': 'http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.personalizations.到'}]}

请问有人知道为什么吗?

phi*_*ash 5

Twilio SendGrid 开发人员布道者在这里。

将多个密件抄送添加到个性化对象时,您需要循环遍历电子邮件地址并单独添加它们。

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)
Run Code Online (Sandbox Code Playgroud)

查看此邮件示例,了解如何使用个性化的各个部分。