Reputation: 11491
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", "https://api.sendgrid.com");
Email from = new Email("[email protected]");
String subject = "Hello World from the SendGrid CSharp Library";
Email to = new Email("[email protected]");
Content content = new Content("text/plain", "Textual content");
Mail mail = new Mail(from, subject, to, content);
Email email = new Email("[email protected]");
mail.Personalization[0].AddTo(email);
dynamic response = await sg.client.mail.send.post(requestBody: 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 EnvironmentVariableTarget.User
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.
Upvotes: 8
Views: 13001
Reputation: 135
Put key directly , do not use System.getenv(KEY)
String key = "YOUR KEY";
SendGrid sg = new SendGrid(key);
Upvotes: -2
Reputation: 9814
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.
Upvotes: 5