0

Everything works fine on Postman with x-www-from-urlencoded and basic auth. Now trying to get my hands dirty, I just get status code 200 with nothing on mailgun, no logs recorded.

using (var client = new HttpClient())
{
  client.BaseAddress = new Uri("https://api.mailgun.net/v3");

  client.DefaultRequestHeaders.Authorization = 
     new AuthenticationHeaderValue("api", "key-withheld-till-a-verdict-has-passed");

  var msg = new List<KeyValuePair<string, string>>
  {
    new KeyValuePair<string, string>("from",
        $"Excited User <mailgun@sandboxSOMEGUIDHERE.mailgun.org>"),
    new KeyValuePair<string, string>("to","approved-to-receive@mailgun"),
    new KeyValuePair<string, string>("subject", "Test Please Do Not Reply"),
    new KeyValuePair<string, string>("text","Thanks for borrowing me your inbox")
  };

  var request = new HttpRequestMessage(HttpMethod.Post, 
     "sandboxSOMEGUIDHERE.mailgun.org/messages");

  request.Content = new FormUrlEncodedContent(msg);

  var response = await client.SendAsync(request);
  // I get 200 status code

  var result = await response.Content.ReadAsStringAsync(); 
  //I get result = "Mailgun Magnificent API"         
}
rethabile
  • 3,029
  • 6
  • 34
  • 68
  • That doesn't seem like the correct response. You sure you're using the correct URL/API endpoint? – Blue Apr 21 '17 at 12:59
  • I tested with `Postman` and everything worked perfect. – rethabile Apr 21 '17 at 13:01
  • Have a look [here](http://stackoverflow.com/questions/18924996/logging-request-response-messages-when-using-httpclient) and log your request. Look for differences between the postman request and the c# request. – Blue Apr 21 '17 at 13:04

1 Answers1

2

First, it turns out I was getting the BaseAddress not right. I had to place a slash at the end of the BaseAddress.

 client.BaseAddress = new Uri("https://api.mailgun.net/v3/");

without the slash, I was posting to (note v3 is missing),

https://api.mailgun.net/sandboxSOMEGUIDHERE.mailgun.org/messages

After sorting that out, another problem emerged 401 - ANAUTHORIZED. And with the help of this SO answer I do,

var byteArray = new UTF8Encoding()
    .GetBytes("api:key-withheld-till-a-verdict-has-passed");
client.DefaultRequestHeaders.Authorization =
     new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

But the reason why mailgun was responding with Ok still remain mysterious. To investigate further, I used Postman to post to,

https://api.mailgun.net/sandboxSOMEGUIDHERE.mailgun.org/messages

and to my surprise, Mailgun mysteriously responded with Ok.

Community
  • 1
  • 1
rethabile
  • 3,029
  • 6
  • 34
  • 68