如何通过Template_id和API Key保存SendGrid动态模板HTML代码以回溯历史版本?
解决方案:通过SendGrid API保存动态模板HTML内容
核心思路
直接调用SendGrid的模板详情API,传入API Key和目标Template ID,拉取当前激活版本的HTML内容,再保存到本地文件即可满足需求。
步骤实现
1. 编写API请求脚本拉取模板HTML
使用Python发送GET请求获取模板详情,提取激活版本的HTML内容:
import requests def fetch_sendgrid_template_html(api_key, template_id): # SendGrid模板详情接口 api_endpoint = f"https://api.sendgrid.com/v3/templates/{template_id}" request_headers = { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json" } response = requests.get(api_endpoint, headers=request_headers) response.raise_for_status() # 抛出HTTP请求错误 template_info = response.json() # 筛选出当前激活的模板版本(active=1表示激活状态) active_version = next( (v for v in template_info["versions"] if v["active"] == 1), template_info["versions"][0] # 兜底取第一个版本 ) return active_version["html_content"]
2. 保存HTML到本地文件
将拉取到的HTML内容写入本地文件,方便后续预览:
def save_html_content(html_str, save_path): with open(save_path, "w", encoding="utf-8") as file: file.write(html_str) # 示例调用 if __name__ == "__main__": YOUR_API_KEY = "替换为你的SendGrid API密钥" TARGET_TEMPLATE_ID = "替换为目标模板ID" OUTPUT_FILE = "sendgrid_current_template.html" try: template_html = fetch_sendgrid_template_html(YOUR_API_KEY, TARGET_TEMPLATE_ID) save_html_content(template_html, OUTPUT_FILE) print(f"模板已成功保存至:{OUTPUT_FILE}") except Exception as err: print(f"操作失败:{str(err)}")
关键注意事项
- 权限要求:确保你的SendGrid API Key拥有
template.read权限,否则会返回403权限错误 - 多版本处理:如果模板存在多个版本,代码中通过
active字段筛选当前正在使用的版本,避免拉取到旧内容 - 自动化更新:可以将脚本配置为定时任务(如Linux cron、Windows任务计划),定期拉取并保存最新模板,无需手动操作
内容的提问来源于stack exchange,提问作者Farhan Amin
相关产品推荐
相关产品推荐

