Shyamal Parikh Shyamal Parikh - 1 month ago 65
C# Question

SendGrid V3 api with C# not able to send mail

This is the code I am using. For some reason it gives an error: 'UnAuthorised'. Any ideas why this may be happening. The Api-key is correctly configured.

String apiKey = Environment.GetEnvironmentVariable("SG.7cSY-INMQnCwIzmonlgZvA.zNtNDycx......", EnvironmentVariableTarget.User);
dynamic sg = new SendGrid.SendGridAPIClient(apiKey, "https://api.sendgrid.com");

Email from = new Email("account@id.com");
String subject = "Hello World from the SendGrid CSharp Library";
Email to = new Email("someone@gmail.com");
Content content = new Content("text/plain", "Textual content");
Mail mail = new Mail(from, subject, to, content);
//Email email = new Email("test2@example.com");
//mail.Personalization[0].AddTo(email);

String ret = mail.Get();

string requestBody = ret;
Console.WriteLine(ret);

try
{
dynamic response = sg.client.mail.send.beta.post(requestBody: requestBody);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Body.ReadAsStringAsync().Result);
Console.WriteLine(response.Headers.ToString());
}
catch (Exception ex) {
Console.WriteLine("SendGrid Error: {0}",ex.Message);
}

Answer

In this line of code:

String apiKey = Environment.GetEnvironmentVariable("SG.7cSY-INMQnCwIzmonlgZvA.zNtNDycx......", EnvironmentVariableTarget.User);

the first parameter is the name of the environment variable that holds the value of your SendGrid API Key, scoped to the user's account. If you are not using environment variables and are comfortable with putting your API Key in your code (not recommended, but this will allow you test that it works), you would do:

String apiKey = "SG.7cSY-INMQnCwIzmonlgZvA.zNtNDycx......";
Comments