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

如何用SendGrid Python单次API调用批量发送带专属附件的邮件?

如何通过单次SendGrid API调用完成带专属附件的批量邮件发送

现有三个收件邮箱:user1@example.com、user2@example.com、user3@example.com,对应三个专属附件文件user1.xlsx、user2.xlsx、user3.xlsx,需为每个用户发送带有其专属附件的邮件。目前采用循环发送的方式(如下代码片段),认为该方案并非最优,请问是否可通过单次SendGrid API调用完成批量发送?

for user, attachment_file in zip(users, attachment_files):
    message = Mail(from_email=from_email, to_emails=user)
    attachment = Attachment(attachment_file)
    message.attachment = [attachment]

    send_grid_client.send(message)

可以通过SendGrid的**Personalizations(个性化设置)**功能实现单次API调用完成批量发送,每个收件人可配置专属附件,无需循环调用API。

实现思路

  • 构建包含所有收件人个性化配置的邮件对象,每个personalization项对应一个收件人及其专属附件。
  • 将所有附件先添加到邮件的全局附件列表,再在对应收件人的个性化配置中指定仅该收件人可见的附件ID。

示例代码

import base64
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail, Attachment, Personalization, To

# 配置基础信息
from_email = "your-sender@example.com"
users = ["user1@example.com", "user2@example.com", "user3@example.com"]
attachment_paths = ["user1.xlsx", "user2.xlsx", "user3.xlsx"]

# 初始化邮件对象
message = Mail(from_email=from_email)
message.subject = "您的专属附件"
message.html_content = "<p>您好,附件为您的专属文件,请查收。</p>"

# 处理附件并添加到邮件,同时记录每个附件的ID和对应收件人
personalizations = []
for idx, (user, file_path) in enumerate(zip(users, attachment_paths)):
    # 读取附件文件并编码为base64
    with open(file_path, "rb") as f:
        file_data = f.read()
    encoded_file = base64.b64encode(file_data).decode()
    
    # 创建附件对象,设置唯一ID
    attachment = Attachment()
    attachment.content = encoded_file
    attachment.filename = file_path.split("/")[-1]
    attachment.type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    attachment.disposition = "attachment"
    attachment.content_id = f"attachment_{idx}"  # 唯一标识附件
    
    # 添加附件到邮件全局列表
    message.attachments.append(attachment)
    
    # 创建该收件人的个性化配置,指定仅显示对应附件
    to = To(email=user)
    personalization = Personalization()
    personalization.add_to(to)
    # 配置仅该收件人可见的附件ID
    personalization.dynamic_template_data = {"attachments": [{"content_id": f"attachment_{idx}"}]}
    
    personalizations.append(personalization)

# 将所有个性化配置添加到邮件
message.personalizations = personalizations

# 发送邮件
try:
    sg = SendGridAPIClient("your-sendgrid-api-key")
    response = sg.send(message)
    print(f"邮件发送成功,状态码: {response.status_code}")
except Exception as e:
    print(f"发送失败: {e.message}")

关键说明

  • Personalizations:每个个性化项独立配置收件人、专属内容(包括附件),SendGrid会自动为每个收件人生成对应版本的邮件。
  • 附件ID关联:通过content_id将附件与特定收件人绑定,确保每个用户只能看到自己的专属附件。
  • API调用效率:单次调用即可完成所有邮件发送,减少网络请求开销,提升发送效率。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 19:12:17