Home > database >  C# rest api mail gun gives forbiden access status
C# rest api mail gun gives forbiden access status

Time:11-24

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 api base URL

So, base URL shouldn't be https://api.mailgun.net/v3/ but 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

  • Related