如何使用SendGrid API获取细分列表的全部联系人?
获取SendGrid细分列表全部联系人邮箱的解决方案
问题说明
调用SendGrid API获取细分列表联系人时,默认仅返回前50个样本联系人,无法直接获取全部数据。需要通过分页请求结合limit和offset参数遍历所有联系人。
实现思路
- 改用
marketing.contacts.list接口,通过segment_ids参数指定目标细分列表ID,过滤出该列表下的所有联系人。 - 每次请求设置
limit(最大支持1000),通过offset逐步偏移请求位置,直到返回的联系人数量不足limit,确认已获取全部数据。 - 从每一页响应中提取邮箱字段,汇总成完整列表。
完整代码示例
import os from sendgrid import SendGridAPIClient import json def get_all_segment_contacts(segment_id): sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) all_emails = [] limit = 1000 # 接口允许的最大单页返回量 offset = 0 while True: # 构造分页请求参数 params = { 'limit': limit, 'offset': offset, 'segment_ids': segment_id } response = sg.client.marketing.contacts.list.get(query_params=params) data = json.loads(response.body) current_page_contacts = data.get('result', []) # 提取当前页的邮箱地址 page_emails = [contact['email'] for contact in current_page_contacts if 'email' in contact] all_emails.extend(page_emails) # 若当前页数据不足limit,说明已到最后一页,终止循环 if len(current_page_contacts) < limit: break # 更新偏移量,准备下一页请求 offset += limit return all_emails # 使用示例 segment_id = "你的细分列表ID" full_email_list = get_all_segment_contacts(segment_id) print("全部联系人邮箱列表:", full_email_list)
关键说明
- 接口修正:原代码调用的
segments._(segment_id).get()仅返回细分列表元数据和样本联系人,无法获取全量数据,需替换为marketing.contacts.list接口。 - 分页逻辑:
limit控制单页返回数量,offset控制起始位置,每次请求后累加limit实现翻页。 - 终止判断:当单页返回数据量小于
limit时,说明已遍历完所有联系人,停止循环。
内容的提问来源于stack exchange,提问作者Allen Chen
相关产品推荐
相关产品推荐

