Modestas Vacerskas
Modestas Vacerskas

Reputation: 55

C# rest api mail gun gives forbiden access status

Good day, I am trying now to do email vertification, and followed all instructions but i get response status Unauthorized

private bool SendEmail(string body, string email)
    {
        //create client
        RestClient client = new RestClient("https://api.eu.mailgun.net/v3");

        client.Authenticator =
            new HttpBasicAuthenticator("api",
            "02a4bca7b2e0c72e98841b20beef1585-69210cfc-a7bc0929");

        var request = new RestRequest();

        request.AddParameter("domain", "sandbox4706f89b4150439ebca3c380f3fa96d0.mailgun.org");
        request.Resource = "{domain}/messages";
        request.AddParameter("from", "Ecommerce sandbox Mail<[email protected]>");
        request.AddParameter("to", email);
        request.AddParameter("subject", "Email Vertfication Email");
        request.AddParameter("text", body);
        request.Method = Method.Post;

        var response = client.Execute(request);

        return response.IsSuccessful;

    }

Do anyone had the same problem? I am conecting from EU so changed rest Client from https://api.mailgun.net/v3 to https://api.eu.mailgun.net/v3 If I use https://api.mailgun.net/v3 I get response status Unauthorized.

Upvotes: 0

Views: 443

Answers (1)

Nino
Nino

Reputation: 7095

Seems like Mailgun changed something in API but forgot to change the documentation. If you go to your domain dashboard and select API, you can see that base URL is different from the one in example

api base URL

So, base URL shouldn't be https://api.mailgun.net/v3/ but https://api.mailgun.net/v3/sandbox....mailgun.org`

Also, make sure that email you're sending to is added to Authorized Recipients for your domain (see how to add it in knowledge base)

enter image description here

Once you have correct base URL and authorized (and verified recipient), you can send your email. So, in your example, it would be like this (look at comments also):

//note the URL with domain
RestClient client = new RestClient("https://api.eu.mailgun.net/v3/sandbox4706f89b4150439ebca3c380f3fa96d0.mailgun.org");

client.Authenticator =
    new HttpBasicAuthenticator("api",
    "02a4bca7b2e0c72e98841b20beef1585-69210cfc-a7bc0929");

var request = new RestRequest();

//request.AddParameter("domain", ... is not needed anymore becasue of base URL
//also, Resource is now without {domain} parameter
request.Resource = "/messages";
request.AddParameter("from", "Ecommerce sandbox Mail<[email protected]>");
//this mail should be authorized recipient
request.AddParameter("to", email);
request.AddParameter("subject", "Email Vertfication Email");
request.AddParameter("text", body);
request.Method = Method.Post;

var response = client.Execute(request);

return response.IsSuccessful;

... And that should send the email without Unauthorized error

Upvotes: 1

Related Questions