简体   繁体   中英

Mandrill API response with HTTP Status 500

I've been trying to get my MVC web app to send emails using a subscription with Mandrill API to no avail. This Mandrill API works by POSTing a JSON object to a specific endpoint. It looks pretty simple and straight-forward and that's why it's so frustrating that everytime I tried to send an email message I get an response from Mandrill with nothing more than a "500 Internal Server Error" no extra information or anything else.

Interestingly, Mandrill API has a public test tool that you can use to test their API. So, I went in and passed exactly the same JSON object my application is sending when receiving that annoying Http Error and the email message is sent without any issues. So basically I have no problems sending the same email through their Test Tool but it fails when my application attempts to send it.

Please find below the delegated to send the email message. It's not yet re-factored...sorry...

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;
  }

And of course, it fails when trying to get the response

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

Any help will be greatly appreciated

Ok, after digging around Mandrill API docs in a search for clues on what needed to be taken into account to make an API call (it didn't seem to be that straight-forward) I decided to install a NuGet package that is actually a .NET wrapper around the Mandrill API.

After making some adjustments the code looked similar to the following...

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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM