使用Godot结合SendGrid API发送邮件的问题与解决
Godot调用SendGrid API发送邮件返回400错误的解决方法
问题背景
在Godot游戏引擎中通过HTTP请求调用SendGrid API发送邮件时,持续收到400错误响应。此前已成功使用该API完成获取邮件模板等操作,重点排查personalization部分后仍未解决问题,最终已定位并修复所有错误。
原错误代码
extends Control var send_email_url = "https://api.sendgrid.com/v3/mail/send" onready var http = $HTTPRequest var auth_key = "authkey replaced" var header_content = "Content-Type: application/json" var email_content = '{"personalizations":[{"to":[{"email":"outofemail2@gmail.com"}],"from":[{"email":"botemail@gmail.com","name":"name2"}]}],"from":{"email":"botemail@gmail.com"},"subject":"Hello, World!","content":[{"type":"text/plain","value":"Heya!"}]}' func _on_new_order_btn_pressed(): get_tree().change_scene("res://Scenes/soft_new_order.tscn") func _on_Button_pressed(): http.request(send_email_url,[auth_key,header_content, email_content],true, HTTPClient.METHOD_POST) func _on_HTTPRequest_request_completed(result, response_code, headers, body): var output = body.get_string_from_utf8() print(response_code) print(output)
错误原因分析
原代码存在三个核心问题:
- 认证头格式不规范:
auth_key仅填写密钥,缺少SendGrid要求的Authorization: Bearer前缀,不符合API认证规则。 - 请求体传递错误:将邮件内容
email_content混入请求头数组,而非作为请求体参数传递,导致API无法解析有效内容。 - JSON结构冗余:
personalizations数组内额外嵌套from字段,SendGrid API要求from字段需放在JSON根层级,冗余字段触发格式校验失败。
解决后的可用代码
extends Control var send_email_url = "https://api.sendgrid.com/v3/mail/send" onready var http = $HTTPRequest var auth_key = "Authorization: Bearer INSERT KEY HERE" var header_content = "Content-Type: application/json" var email_content = { "personalizations" : [ { "to" : [ { "email" : "emai_receiver@gmail.com" } ] }, ], "from" :{ "email" : "email_sender@gmail.com" }, "subject" : "Hello world", "content" : [ {"type" : "text/plain", "value" : "Hello Content"}, ] } func _on_Button_pressed(): http.request(send_email_url,[auth_key,header_content],true, HTTPClient.METHOD_POST,to_json(email_content)) func _on_HTTPRequest_request_completed(result, response_code, headers, body): var output = body.get_string_from_utf8() print(response_code) print(output)
关键修正说明
- 补全认证头格式:为
auth_key添加Authorization: Bearer前缀,匹配SendGrid API的认证要求。 - 调整参数传递方式:将
email_content通过to_json()转换为标准JSON字符串后,作为http.request的请求体参数单独传递。 - 清理冗余结构:移除
personalizations内部的from字段,将from字段移至JSON根层级,符合API请求格式规范。
内容的提问来源于stack exchange,提问作者cloud99
相关产品推荐
相关产品推荐

