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

PHP使用CURL调用SendGrid API设置Message-ID时发件人邮箱报错

问题根源

你遇到的错误是因为SendGrid v2和v3 API的请求格式不兼容:

  • 你当前调用的api/mail.send.json是SendGrid v2 API的端点,它只支持扁平结构的参数(就是你之前正常工作的那种格式);
  • 但你构造的请求体是v3 API的嵌套结构,v2接口无法解析其中的from字段,因此报错“发件人邮箱为空”。
两种解决方案

方案1:在v2 API中直接设置Message-ID

不需要切换到v3格式,保持你原来的v2参数结构,只需要新增headers参数(注意要传JSON字符串格式):

$params = array(
    'to'        => $to,
    'subject'   => $subject,
    'html'      => $message,
    'from'      => $from,
    'fromname'  => $from_name,
    // 将Message-ID封装为JSON字符串传入
    'headers'   => json_encode(array("Message-ID" => "<253618-testing-header>"))
);

// 发送请求的代码保持你原来的逻辑即可
$request = $url . 'api/mail.send.json';
$cr = curl_init($request);
curl_setopt($cr, CURLOPT_POSTFIELDS, http_build_query($params)); // v2用表单格式提交
curl_setopt($cr, CURLOPT_POST, true);
curl_setopt($cr, CURLOPT_HTTPHEADER, array("Authorization: Bearer test"));
curl_setopt($cr, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($cr);
$out = json_decode($response, true);

方案2:切换到SendGrid v3 API(推荐)

如果后续需要更多高级功能,建议直接升级到v3 API,步骤如下:

  1. 修改请求端点为v3的地址;
  2. 添加Content-Type: application/json请求头(v3要求JSON格式的请求体);
  3. 保留你原来的v3结构请求体。

修改后的完整代码:

$params = [
    "personalizations" => [
        [
            "to" => [
                ["email" => "test@test.com"]
            ],
            "subject" => "testing subject for mail"
        ]
    ],
    "from" => [
        "email" => "check@check.com",
        "name" => $from_name
    ],
    "content" => [
        [
            "type" => "text/html",
            "value" => $message
        ]
    ],
    "headers" => [
        "Message-ID" => "<253618-testing-header>"
    ]
];

// v3 API 官方端点
$request = 'https://api.sendgrid.com/v3/mail/send';
$cr = curl_init($request);
curl_setopt($cr, CURLOPT_POSTFIELDS, json_encode($params));
curl_setopt($cr, CURLOPT_POST, true);
// 必须添加Content-Type头,同时保留授权头
curl_setopt($cr, CURLOPT_HTTPHEADER, array(
    "Authorization: Bearer test",
    "Content-Type: application/json"
));
curl_setopt($cr, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($cr);
$out = json_decode($response, true);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 15:36:17