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(); }
额外验证项
- 确认API Key确实包含
mail.read权限(即使是完全访问权限,也可在SendGrid控制台的API Key页面核对权限列表) - 确认「additional email activity history」服务已生效,部分付费服务可能需要几分钟激活时间
内容的提问来源于stack exchange,提问作者theok
相关产品推荐
相关产品推荐

