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

SendGrid API v3筛选邮件活动时出现authorization required授权错误

问题排查与解决方案

你的代码存在几个核心问题导致了400错误:

  • 用HTML实体"替代了PHP的双引号,导致json_decode解析后的参数格式不符合API要求
  • SendGrid PHP客户端的get方法要求查询参数为关联数组,而非json_decode生成的stdClass对象
  • 查询语句中邮箱地址的引号转义方式错误

修正后的代码

require_once 'sendgrid-php.php'; 

$apiKey = getenv('SG.xxxxxxx');
$sg = new \SendGrid($apiKey);

// 直接构造关联数组,规避JSON解析的潜在问题
$query_params = [
    'query' => 'from_email="noreply@xxx.com"',
    'limit' => 10
];

try {
    $response = $sg->client->messages()->get(null, $query_params);
    print $response->statusCode() . "\n";
    print_r($response->headers());
    print $response->body() . "\n";
} catch (Exception $ex) {
    echo 'Caught exception: '.  $ex->getMessage();
}

额外验证项

  1. 确认API Key确实包含mail.read权限(即使是完全访问权限,也可在SendGrid控制台的API Key页面核对权限列表)
  2. 确认「additional email activity history」服务已生效,部分付费服务可能需要几分钟激活时间

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 15:07:49