在Web应用程序中,我们将电子邮件存储在数据库表中。我们从数据库中提取这些内容,替换占位符并发送电子邮件。
我正在尝试使用Sendgrid的web api / v3,我遇到了一个问题。
以下是我准备发送电子邮件的示例:
var sent = false;
try
{
var apiAddress = "https://api.sendgrid.com/v3/mail/send";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiAddress);
request.Headers.Add("Authorization", "Bearer SG.snip");
request.ContentType = "application/json";
request.Proxy = null;
request.Method = "POST";
request.ProtocolVersion = HttpVersion.Version11;
var content = "<p>simple html comment with nothing complex</p>";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string json = "{ \"categories\" :[\"cat1\"],\"personalizations\": [{\"to\": [{\"email\":\"me@domain.com\"}],\"subject\": \"test email\"}],\"from\": {\"email\": \"email@domain.com\"},\"content\": [{\"type\": \"text/html\",\"value\": \"<html>" + content + "</html>\"}]}";
streamWriter.Write(json);
}
WebResponse response = request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
sent = true;
}
catch (Exception ex)
{
sent = false;
}
这个发送正常,但是当我的内容很复杂时,API返回400 BAD REQUEST并且不发送电子邮件。
我遇到问题的电子邮件里面有引号,例如这里是电子邮件的精简版本:
<!DOCTYPE html><html lang="en"><body>hi</body></html>
如果我用反斜杠转义引号,它可以正常工作。我是否必须通过整个HTML转义每个引用?