You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用SendGrid V3 API(Python)给多个收件人发送邮件

How to Send Emails to Multiple Recipients with SendGrid V3 API (Python)

Got it, let's get this sorted for you! The problem with your current code is that you're passing a single Email object directly to the Mail constructor, which only handles one recipient. SendGrid's V3 API uses personalizations to manage multiple recipients (and even per-recipient customizations), so here's how to adjust your code:

Modified Code with Multiple Recipients

import sendgrid
from sendgrid.helpers.mail import *

sg = sendgrid.SendGridAPIClient(apikey="SG.xxxxxxxx")
from_email = Email("FROM EMAIL ADDRESS")
subject = "Sending with SendGrid is Fun"
content = Content("text/plain", "and easy to do anywhere, even with Python")

# Initialize the Mail object without specifying a single to_email
mail = Mail(from_email, subject, None, content)

# Create a Personalization instance to hold all recipients
personalization = Personalization()
# Add each recipient individually
personalization.add_to(Email("xxx@gmail.com"))
personalization.add_to(Email("yyy@gmail.com"))

# Optional: Add CC/BCC recipients if needed
# personalization.add_cc(Email("cc@example.com"))
# personalization.add_bcc(Email("bcc@example.com"))

# Attach the personalization to your mail object
mail.add_personalization(personalization)

response = sg.client.mail.send.post(request_body=mail.get())
print(response.status_code)
print(response.body)
print(response.headers)

How This Works

  • Instead of passing a single to_email to the Mail constructor, we leave that parameter as None and use a Personalization object to manage recipients.
  • The Personalization class lets you add multiple to (or cc/bcc) addresses using add_to() (or add_cc()/add_bcc()).
  • If you need to send customized content to each recipient (like unique subject lines or personalized messages), you can create multiple Personalization objects (one per recipient) and add them all to the mail object.

Alternative: Directly Populate the Personalizations List

If you prefer a more concise approach, you can directly set the personalizations list on the Mail object without using the helper methods:

mail.personalizations = [
    {
        "to": [
            {"email": "xxx@gmail.com"},
            {"email": "yyy@gmail.com"}
        ]
        # Optional: Add "cc" or "bcc" arrays here too
    }
]

Either approach will work—using the Personalization helper class just makes it easier to avoid typos and leverage SendGrid's built-in validation.

内容的提问来源于stack exchange,提问作者P113305A009D8M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:35:22