我一直在尝试使用 Sendgrid API 发送 HTML 电子邮件,但未能成功将 html 嵌入到 json 请求中。
这是我尝试发送的 html 示例 (emailtpl
):
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head><body></body></html>
我尝试过的事情:
- html.EscapeString(emailtpl)
- strconv.Quote(emailtpl)
- 在 json 模板中使用反引号 `
- 将 json 模板中的值用单引号括起来。
- base64.StdEncoding.EncodeToString([]byte(emailtpl)) 仅显示 base64 乱码。
项目 #1 和 #5 是 Sendgrid 接受的唯一解决方案,但发送的 html 不正确(如屏幕截图所示)。
项目 #2 - #4 都会导致状态 400 错误请求。
有谁知道如何将 html 嵌入到 Sendgrid 接受并正确呈现的 Sendgrid API 请求中?
最佳答案
查看 Sendgrid api 文档,它看起来应该接受 html。您需要在 json 字符串中正确转义 html(并设置 content->type = "text/html")。
在您的示例模板中,我看到的唯一问题是元标记中的双引号。作为确保一切正常的快速测试,我会尝试发送以下 html 字符串:
<html><head></head><body>Hi!</body></html>
如果该 html 字符串成功,则您需要转义原始 html 字符串示例。我看到的唯一无效字符是双引号,需要在 json 中使用反斜杠对其进行转义。我不确定 go 是否对此有特定的功能,但看起来应该可以:
// import "strings"
strings.Replace(emailtpl, `"`, `\"`, -1)
关于json - 如何以 Sendgrid API 接受的格式将 html 嵌入到 json 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49625281/