如何解决在经典asp中将json数据发布到SendGrid API v3时,使用新行发布textarea标签数据失败 有用的链接
我尝试在 html 中发布 textarea 数据,它可以包含新行作为 Sendgrid API 的文本/纯文本的内容。 但它根本没有成功..我需要一些帮助。
■Html
表单中的Textarea标签
■ServerSide Program(ASP) 将文本区域数据作为正文发布到 Sendgrid
'Send Mail with SendGrid
Sub SendMailWithApiKey(strTo,strFrom,strTitle,strBody)
Set xmlhttp = CreateObject("Msxml2.ServerXMLHTTP.6.0")
xmlhttp.open "POST","https://api.sendgrid.com/v3/mail/send",false
xmlhttp.setRequestHeader "Authorization","Bearer Some API Key of sendgrid"
xmlhttp.SetRequestHeader "Content-Type","application/json"
xmlhttp.SetRequestHeader "X-Requested-With","XMLHttpRequest"
xmlhttp.send "{ ""personalizations"": [ { ""to"": [{""email"": """ & strTo &"""}] } ],""from"": {""email"": """ & strFrom &"""},""subject"": """ & strTitle &""",""content"": [ { ""type"": ""text/plain"",""value"": """ & strBody &""" }] }"
response.addheader "Content-Type","application/json;charset=UTF-8"
Response.Charset = "UTF-8"
pageReturn = xmlhttp.responseText
Response.AppendToLog xmlhttp.responseText
Set xmlhttp = nothing
response.write pageReturn
End Sub
“strBody”是 textarea 用户写入的值。
如果我像“测试”一样写一行,它运行良好并收到邮件。 但是当我在文本区域中像下面这样写时它失败了。
"测试
测试
测试
"
我从 sendgrid 收到 400 错误。
{"errors":[{"message":"Bad+Request","field":null,"help":null}]}
我申请你的帮助。
解决方法
请记住在为 SendGrid API 构建经典 ASP 脚本库时遇到此问题,因为返回的错误不是很有用,需要花一点时间来诊断问题。
问题是因为 SendGrid 需要 JSON 作为输入,因此传递多行字符串(包含回车、换行等)会破坏 JSON 解析。要解决此问题,只需在 strBody
上进行替换,将行尾转换为 \n
。
类似这样,在调用 Send()
方法之前;
strBody = Replace(strBody & "",vbCrLf,"\n")
你可能会发现你需要对其他值做同样的事情;
strBody = Replace(strBody & "","\n")
strBody = Replace(strBody & "",vbTab,"\t")
如果您使用 HTML,您需要将行尾转换为 HTML 换行符 <br />
。
同样只需要一个 Replace()
;
strBody = Replace(strBody & "",vbNewLine,"<br />")
有用的链接
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。