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

如何通过SendGrid API自动获取邮件活动CSV无需管理员参与

解决方案

要实现自动化获取SendGrid邮件活动CSV,无需依赖管理员邮箱转发,可按以下步骤操作:

1. 发起CSV导出请求(你已完成此步)

用现有代码触发异步导出任务:

import os
import time
from sendgrid import SendGridAPIClient

sg = SendGridAPIClient(api_key=os.environ.get('SENDGRID_API_KEY'))
# 发起导出请求
export_response = sg.client.messages.download.post()
print("导出任务已发起,状态:", export_response.body)

2. 轮询任务状态,获取download_uuid

SendGrid CSV导出为异步执行,需通过GET /messages/download端点轮询任务状态,直到任务完成并提取download_uuid:

def get_completed_export_uuid():
    while True:
        # 获取所有导出任务列表
        tasks_response = sg.client.messages.download.get()
        tasks = tasks_response.json()
        # 筛选已完成的任务,按创建时间倒序取最新一条
        completed_tasks = [task for task in tasks if task['status'] == 'completed']
        if completed_tasks:
            latest_task = sorted(completed_tasks, key=lambda x: x['created_at'], reverse=True)[0]
            return latest_task['download_uuid']
        # 未完成则等待后重试,建议间隔30-60秒避免触发限流
        print("导出任务尚未完成,等待60秒后重试...")
        time.sleep(60)

# 获取目标任务的download_uuid
download_uuid = get_completed_export_uuid()
print("获取到下载UUID:", download_uuid)

3. 下载CSV文件

拿到download_uuid后,调用对应端点下载CSV到本地:

def download_csv(download_uuid):
    # 发起下载请求
    download_response = sg.client.messages.download._(download_uuid).get()
    # 将响应内容写入本地文件
    with open('sendgrid_email_activity.csv', 'wb') as f:
        f.write(download_response.body)
    print("CSV文件已成功下载:sendgrid_email_activity.csv")

download_csv(download_uuid)

关键注意事项

  • API权限:你的SendGrid API Key必须拥有mail.read权限,否则无法访问导出任务和下载CSV。
  • 轮询间隔:避免过于频繁请求,遵守SendGrid的API限流规则,建议间隔30-60秒。
  • 任务筛选:若存在多个导出任务,需通过created_at时间筛选你刚发起的任务,避免获取旧任务的UUID。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 03:48:23