SendGrid发送邮件前如何验证模板ID有效性及获取活跃模板列表?
SendGrid 7.2 动态模板验证方案
一、获取活跃模板列表(缓存复用)
通过SendGrid Templates API拉取所有活跃模板,缓存后用于前置验证,减少单次验证的API请求:
// 初始化SendGrid客户端 $sendgrid = new \SendGrid(getenv('SENDGRID_API_KEY')); try { // 获取所有模板数据 $response = $sendgrid->client->templates()->get(); $templates = json_decode($response->body(), true); // 筛选出状态为active的模板ID $activeTemplateIds = []; foreach ($templates as $template) { if ($template['status'] === 'active') { $activeTemplateIds[] = $template['id']; } } // 将$activeTemplateIds存入缓存(如Redis、文件),避免重复调用API } catch (\Exception $e) { throw new \Exception("获取模板列表失败: " . $e->getMessage()); } // 发送前校验模板ID if (!in_array($templateId, $activeTemplateIds)) { throw new \Exception("无效或已停用的模板ID"); }
二、单个模板ID直接验证
直接调用单模板详情接口,精准验证目标模板的状态:
$sendgrid = new \SendGrid(getenv('SENDGRID_API_KEY')); try { // 请求目标模板的详情 $response = $sendgrid->client->templates()->_($templateId)->get(); if ($response->statusCode() !== 200) { throw new \Exception("模板ID不存在"); } $template = json_decode($response->body(), true); if ($template['status'] !== 'active') { throw new \Exception("模板已停用"); } } catch (\Exception $e) { throw new \Exception("验证模板失败: " . $e->getMessage()); }
关键注意点
- 确保API密钥拥有
template.read权限,否则会返回权限错误。 - 频繁调用API会触发速率限制,建议对模板列表缓存(比如每1小时刷新一次)。
- 即使做了前置验证,发送邮件时仍需保留原有的
statusCode() != 202判断,覆盖验证后模板被删除的极端场景。
内容的提问来源于stack exchange,提问作者Dula
相关产品推荐
相关产品推荐

