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

如何使用SendGrid与Python批量验证大量邮箱地址?

SendGrid API批量验证邮箱的Python实现方案

SendGrid提供批量邮箱验证的API接口,无需逐个发送请求,适合处理5万+规模的邮箱列表。以下是分步实现指南和代码片段:

准备工作

  • 安装依赖库:pip install requests
  • 确保你的SendGrid API密钥拥有**邮箱验证(Email Validation)**权限

核心代码实现

1. 创建验证批次

首先需要创建一个邮箱验证批次,后续所有邮箱都将添加到这个批次中:

import requests

# 替换为你的SendGrid API密钥
SENDGRID_API_KEY = "your_sendgrid_api_key"
headers = {
    "Authorization": f"Bearer {SENDGRID_API_KEY}",
    "Content-Type": "application/json"
}

def create_validation_batch(batch_name="Monthly Bulk Email Validation"):
    url = "https://api.sendgrid.com/v3/validations/email/batches"
    payload = {"name": batch_name}
    response = requests.post(url, json=payload, headers=headers)
    response.raise_for_status()  # 捕获请求错误
    return response.json()["id"]

2. 批量添加邮箱到批次

为避免单次请求过大导致失败,建议按每1000个邮箱为一组分批提交:

def add_emails_to_batch(batch_id, emails):
    url = f"https://api.sendgrid.com/v3/validations/email/batches/{batch_id}/emails"
    batch_size = 1000  # 可根据SendGrid限制调整
    for idx in range(0, len(emails), batch_size):
        current_batch = emails[idx:idx+batch_size]
        payload = {"emails": current_batch}
        response = requests.post(url, json=payload, headers=headers)
        response.raise_for_status()
        print(f"已成功提交 {len(current_batch)} 个邮箱")

3. 读取邮箱列表并执行验证

从本地文件(如每行一个邮箱的txt文件)读取邮箱,执行批次创建和邮箱提交:

def main():
    # 从txt文件读取邮箱列表,每行一个邮箱
    with open("email_list.txt", "r", encoding="utf-8") as f:
        email_list = [line.strip() for line in f if line.strip()]
    
    # 创建验证批次
    batch_id = create_validation_batch()
    print(f"验证批次创建成功,批次ID: {batch_id}")
    
    # 批量提交邮箱
    add_emails_to_batch(batch_id, email_list)
    
    # 可选:查询批次状态并下载结果(见下方函数)
    # get_validation_results(batch_id)

if __name__ == "__main__":
    main()

4. 查询验证状态并下载结果

验证完成后,可通过API获取结果文件:

def get_validation_results(batch_id):
    url = f"https://api.sendgrid.com/v3/validations/email/batches/{batch_id}"
    response = requests.get(url, headers=headers)
    response.raise_for_status()
    batch_info = response.json()
    
    print(f"批次状态: {batch_info['status']}")
    print(f"已验证邮箱数: {batch_info['completed_count']}/{batch_info['total_count']}")
    
    # 批次完成后下载结果CSV
    if batch_info["status"] == "completed":
        result_response = requests.get(batch_info["results_url"], headers=headers)
        result_response.raise_for_status()
        with open("validation_results.csv", "wb") as f:
            f.write(result_response.content)
        print("验证结果已保存到 validation_results.csv")

注意事项

  • SendGrid批量验证的速率和额度限制取决于你的订阅计划,付费版支持更大规模的批量处理
  • 每个批次最多可容纳100万个邮箱,完全覆盖5万+的需求
  • 验证结果包含每个邮箱的状态(有效、无效、风险邮箱等),可通过CSV文件进一步分析

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 15:02:45