如何使用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_emailto theMailconstructor, we leave that parameter asNoneand use aPersonalizationobject to manage recipients. - The
Personalizationclass lets you add multipleto(orcc/bcc) addresses usingadd_to()(oradd_cc()/add_bcc()). - If you need to send customized content to each recipient (like unique subject lines or personalized messages), you can create multiple
Personalizationobjects (one per recipient) and add them all to themailobject.
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
相关产品推荐
相关产品推荐

