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,步骤如下:
- 修改请求端点为v3的地址;
- 添加
Content-Type: application/json请求头(v3要求JSON格式的请求体); - 保留你原来的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
相关产品推荐
相关产品推荐

