Ashkan Sirous Ashkan Sirous - 1 year ago 345
C# Question

Sendgrid API: The provided authorization grant is invalid, expired, or revoked

I've just created a sendgrid account. Then I went to settings=>API Keys
and clicked on "Create API Key" and gave any possible permission.

Then I've created a c# project, added nuget packages and put my write the hello world code from here

public async Task HelloEmail()
dynamic sg = new SendGrid.SendGridAPIClient("XXX-XXXXXXXXXXXXXXXXXX", "");

Email from = new Email("");

String subject = "Hello World from the SendGrid CSharp Library";
Email to = new Email("");
Content content = new Content("text/plain", "Textual content");
Mail mail = new Mail(from, subject, to, content);
Email email = new Email("");

dynamic response = await mail.Get());

var x=response.StatusCode;
var y = response.Body.ReadAsStringAsync().Result;
var z = response.Headers.ToString();

But I get

Unauthorized =>

"{\"errors\":[{\"message\":\"The provided authorization grant is invalid, expired, or revoked\",\"field\":null,\"help\":null}]}"

In the example, they got the API key from the
is it related to that?

string apiKey = Environment.GetEnvironmentVariable("NAME_OF_THE_ENVIRONMENT_VARIABLE_FOR_YOUR_SENDGRID_KEY", EnvironmentVariableTarget.User);
dynamic sg = new SendGridAPIClient(apiKey);

*The problem is that no one reads messages when creating a key, also Microsoft chooses to show us "API Key ID" which is worst name ever

It is not a duplicate because although the reason was the same, no one would guess it since in c# we use a nuget library, not the api.

Answer Source

Something is wrong with your API key. Check this answer, generate a new key, and double check your permissions.

You also don't need to specify the URL in your SendGrid.SendGridAPIClient. I'd remove that line to reduce hardcoded values.