Note: To the moderator that incorrectly closed this question, it's completely different from the generic nullref question. This is specific to SendGrid.
I believe I'm following pretty close to documented SendGrid usage:
public async Task<string> SendEmailSendGrid(string emailTo, string subject, string body) {
var apiKey = SafeTrim(ConfigurationManager.AppSettings["SendGridAPIKey"]);
var client = new SendGridClient(apiKey);
var from = new EmailAddress(SafeTrim(ConfigurationManager.AppSettings["SendGridEmail"]));
var to = new EmailAddress(emailTo);
var msg = MailHelper.CreateSingleEmail(from, to, subject, string.Empty, body);
try {
var response = await client.SendEmailAsync(msg);
//return response;
return "SUCCESS";
} catch (Exception ex) {
return "ERROR in SendEmailSendGrid(): " + ex.Message;
}
}
And the caller:
var result = utils.SendEmailSendGrid(decodedEmail, "email test", "This is a test email using SendGrid.");
And the error I get every time EVEN THOUGH IT WORKS and the email actually sends and arrives in my inbox:
Object reference not set to an instance of an object.
That error occurs on this line:
var response = await client.SendEmailAsync(msg);
I verified that all my variables are populated as expected - none are null or empty. I am passing an empty string to the plain text param (because I always want HTML contents), but I also tried passing that some content and it made no difference; same error.
A strange thing: this blows up so hard that my catch
block is never entered. Instead, as soon as the exception is thrown, this full-screen window comes up in my VS2022
:
So it is working and sending the email, but why the heavy crash? What am I doing wrong?