我一直试图让我的MVC网络应用程序使用Mandrill API订阅发送电子邮件无济于事。此Mandrill API通过将JSON
对象发布到特定端点来工作。它看起来非常简单和直接,这就是为什么它如此令人沮丧,以至于我每次尝试发送电子邮件时都会收到Mandrill的回复,其中只有一个" 500内部服务器错误& #34;没有额外的信息或其他任何信息。
有趣的是,Mandrill API有public test tool可用于测试其API。因此,当我收到恼人的Http错误并且发送电子邮件时没有任何问题,我进入并传递了我的应用程序发送的完全相同的JSON
对象。所以基本上我通过他们的Test Tool发送相同的电子邮件没有问题,但是当我的应用程序试图发送它时它失败了。
请在下面找到委托发送电子邮件的信息。它还没有重新考虑......对不起......
public bool Send(string to, string toDisplayName, string subject, string body)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://mandrillapp.com/api/1.0/messages/send.json");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
try
{
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = string.Format(@"{{""key"": ""{0}"",""message"": {{""html"": ""{1}"",""subject"": ""{2}"",""from_email"": ""{3}"",""from_name"": ""AppCompear"",""to"": [{{""email"": ""{4}"",""name"": ""{5}"",""type"": ""to""}}],""important"": false}},""async"": false,""ip_pool"": ""Main Pool""}}"
, _setting.Password, body.Replace(@"""", @"\"""), subject, _setting.UserName, to, toDisplayName);
LogManager.Current.LogError(to, "", "", "", null, json);
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
}
catch (WebException wex)
{
LogManager.Current.LogError(to, "", "", "", wex, wex.Message);
}
catch (Exception ex)
{
LogManager.Current.LogError(to, "", "", "", ex, ex.Message);
}
return true;
}
当然,它在尝试获得回复时失败了
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
非常感谢任何帮助
答案 0 :(得分:2)
好的,在搜索Mandrill API文档以寻找线索之后需要考虑什么来进行API调用(它似乎没那么直接)我决定安装一个NuGet包实际上是围绕Mandrill API的.NET包装器。
进行一些调整后,代码看起来类似于以下内容......
Mandrill.EmailMessage message = new Mandrill.EmailMessage();
message.from_email = _setting.UserName;
message.from_name = "Whatever";
message.html = body;
message.subject = subject;
message.to = new List<Mandrill.EmailAddress>()
{
new Mandrill.EmailAddress(to, toDisplayName)
};
Mandrill.MandrillApi mandrillApi = new Mandrill.MandrillApi(_setting.Password, false);
var results = mandrillApi.SendMessage(message);
foreach (var result in results)
{
if (result.Status != Mandrill.EmailResultStatus.Sent)
LogManager.Current.LogError(result.Email, "", "", "", null, string.Format("Email failed to send: {0}", result.RejectReason));
}