如何使用 mailgun API 在电子邮件 subject/html 正文中发送 '&' 符号?

How to send '&' symbol in email subject/html body using mailgun API?

我已经实现了 mailgun API 方法 以使用经典 ASP 在我的网站上发送电子邮件,如本 link 中所述。但是当我们尝试在 subject/text/htmlbody 中发送 '&' symbol'&' symbol 之后的文本不会在电子邮件中发送.

例如:如果我们尝试发送主题为 "A&B Traders" 但使用 mailgun API 发送的电子邮件将显示主题为 "A"。

出现问题是因为我们使用由 & 分隔的查询字符串向 mailgun 发送参数 API 有没有办法绕过内容中的“&”符号并发送查询字符串值,但是它应作为 & 在电子邮件中收到。

我搜索了很多但无法在 mailgun API 文档中找到任何解决方案。

发送电子邮件的示例代码:

Function SendMailSync(toAddress, fromAddress, subject, body, htmlBody)
Dim httpPostData
Dim mailGunMessageUrl
Const MAILGUN_BASE_URL = "https://api.mailgun.net/v3/{DOMAIN HERE}"
Const MAILGUN_API_KEY = "key-{API_KEY}"
httpPostData = "from=" & fromAddress
httpPostData = httpPostData & "&to=" & toAddress
httpPostData = httpPostData & "&subject=" & subject
httpPostData = httpPostData & "&text=" & body
httpPostData = httpPostData & "&html=" & htmlBody
set http = CreateObject("MSXML2.ServerXMLHTTP.6.0")
mailGunMessageUrl = MAILGUN_BASE_URL & "/messages"
http.Open "POST", mailGunMessageUrl, false, "api", MAILGUN_API_KEY
http.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
http.setRequestHeader "Authorization", "Basic AUTH_STRING"
http.Send httpPostdata
If http.status <> 200 Then
    Response.Write "An error occurred: " & http.responseText
End If
SendMailSync = http.responseText
Set http = Nothing
End Function
SendMailSync "adam@example.com", "No Reply noreply@example.com", "A&B Traders", "A&B Traders Welcomes You", ""

修改 SendMailAsync() 函数,以便您 Server.UrlEncode() 传递每个值。例如 subject,只需将其更改为;

httpPostData = httpPostData & "&subject=" & Server.UrlEncode(subject)

这样,当发送 URL 时,subject 查询字符串参数将类似于;

&subject=A%26B%20Traders

如果您想自己测试该方法,您可以使用在线 URL 解码/编码页面,例如 URL Decoder/Encoder

每当通过 Http 请求手动发送数据时,您应该 URL 对所有参数进行编码,这样就不会发生与 ?& 等特殊字符发生冲突的情况。当您提交标准表单时,Internet 浏览器会将此作为其流程的一部分,这就是为什么有些人可能不熟悉为什么在发送手动请求时需要它。


有用的链接