json - 如何以 Sendgrid API 接受的格式将 html 嵌入到 json 中?

标签 json go sendgrid-api-v3 html-escape strconv

我一直在尝试使用 Sendgrid API 发送 HTML 电子邮件,但未能成功将 html 嵌入到 json 请求中。

这是我尝试发送的 html 示例 (emailtpl):

<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head><body></body></html>

我尝试过的事情:

  1. html.EscapeString(emailtpl)
  2. strconv.Quote(emailtpl)
  3. 在 json 模板中使用反引号 `
  4. 将 json 模板中的值用单引号括起来。
  5. base64.StdEncoding.EncodeToString([]byte(emailtpl)) 仅显示 base64 乱码。

项目 #1 和 #5 是 Sendgrid 接受的唯一解决方案,但发送的 html 不正确(如屏幕截图所示)。

escape-butchered

项目 #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/

相关文章:

jquery - 如何防止 .NET JSON 源被缓存

java - 在 Jackson Custom Deserializer 中读取跳过的 child

go - 如何将 exec.Command 的输出通过管道传输到 Golang 中的另一个命令

android - 如何使用 SendGrid Api 在单个电子邮件中发送多个附件?

firebase - 试图弄清楚为什么 Sendgrid 的电子邮件 API 与 Firebase 函数的集成返回 "API key does not start with SG."

javascript - 将 JSON 对象数组分配给 Angular/Typescript 接口(interface)数组

http - 编写每个处理程序的中间件

go - golang的hystrix库“电路断开”而没有“超时”错误

node.js - 总项目未得到响应 sendgrid nodejs Api

json - 使用 Ag-grid 将 JSON 导出到 excel (csv)