Sendgrid 错误 - ValueError('请使用收件人、抄送或密件抄送对象。',)

Jac*_*man 2 python-2.7 sendgrid

我们在谷歌应用引擎标准上使用 sendgrid 6.0.5 python2.7。

以下代码有效

subject = data_sent_obj["subject"]
body_html            = data_sent_obj["body_html"]
body_text            = data_sent_obj["body_text"]

email_id_variable = "info@mycompany.com"
to_email = "info@mycompany.com"         # THIS WORKS
# to_email = Email(email_id_variable)   # THIS DOES NOT WORK

email_message = Mail(
    from_email          = 'info@mycompany.com',
    to_emails           = to_email,
    subject             = subject,                   
    html_content        = body_html)

personalization = Personalization()
personalization.add_to(Email(to_email))
bcc_list = bcc_email_list
for bcc_email in bcc_list:
    personalization.add_bcc(Email(bcc_email))


email_message.add_personalization(personalization)


try:
    sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
    response = sg.send(email_message)
Run Code Online (Sandbox Code Playgroud)

当我们使用

to_email = Email(email_id_variable) we get the following error.
Run Code Online (Sandbox Code Playgroud)
ValueError('Please use a To, Cc or Bcc object.',)
Run Code Online (Sandbox Code Playgroud)

本质上,我们希望将电子邮件发送到变量中的地址。

小智 5

似乎问题本身不是使用变量,而是邮件实现删除电子邮件对象作为 to_emails 中列表的可能性,因此请改用 To 对象:

from sendgrid.helpers.mail import To
...
to_email = To(email_id_variable)
Run Code Online (Sandbox Code Playgroud)

这同样适用于 cc 和 bcc 对象。