1

I have such implementation of sending emails with SendGrid. That works fine, but how I can check if an email was sent correctly, of course, I'm not thinking about cases that email address was not correct one but cases like that SendGrid servers were not available or generally, something obviously wrong during email sending

public class EmailSender : IEmailSender
{
    public string SendGridKey;
    public string SendGridEmail;
    public string SendGridName;

    public EmailSender()
    {
        var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
        SendGridKey = configuration["EmailCredentials:SendGridKey"];
        SendGridEmail = configuration["EmailCredentials:SendGridEmail"];
        SendGridName = configuration["EmailCredentials:SendGridName"];
    }

    public Task SendEmailAsync(string email, string subject, string message)
    {
        return Execute(SendGridKey, subject, message, email);
    }

    public Task Execute(string apiKey, string subject, string message, string email)
    {
        var client = new SendGridClient(apiKey);
        var msg = new SendGridMessage()
        {
            From = new EmailAddress(SendGridEmail, SendGridName),
            Subject = subject,
            PlainTextContent = message,
            HtmlContent = message
        };
        msg.AddTo(new EmailAddress(email));
        msg.SetClickTracking(false, false);
        return client.SendEmailAsync(msg);
    }
}
k507
  • 53
  • 6
  • 1
    I used the NodeJS sdk, but that should return a tracking number and status code as a result of calling `sendEmail...`. It looks like your code is only set up to return a void Task with no response. [docs](https://github.com/sendgrid/sendgrid-csharp/blob/main/src/SendGrid/Response.cs) – ps2goat Jan 16 '22 at 21:27

2 Answers2

2

Take a look at this post maybe you get to know how to check the return value of the mail sending method. SendGrid SendEmailAsync() - uncatchable exception thrown

2

SendEmailAsync returns a Task<response> which you can read to determine delivery information (see use cases in the repo docs) while everything in your Excute task could throw an exception if you have the wrong API key, SendGrid is down, or you get some other error (see: troubleshooting in the repo docs). Putting this together:

public async Task Execute(string apiKey, string subject, string message, string email)
{
  try {
    var client = new SendGridClient(apiKey);
    var msg = new SendGridMessage()
    {
      From = new EmailAddress(SendGridEmail, SendGridName),
      Subject = subject,
      PlainTextContent = message,
      HtmlContent = message
    };
    msg.AddTo(new EmailAddress(email));
    msg.SetClickTracking(false, false);
    var response=await client.SendEmailAsync(msg);
    Console.WriteLine(response.IsSuccessStatusCode 
      ? "Email queued successfully!" 
      : "Something went wrong!");
  } 
  catch (Exception ex) 
  {
    //Decode the message and log to console (for example)
    SendGridErrorResponse errorResponse = 
      JsonConvert.DeserializeObject<SendGridErrorResponse>(ex.Message);
    Console.WriteLine(ex.Message);
  }

There's a useful Twilio blog post on the topic: Send Emails with C# and .NET 6 using the SendGrid API

Rudu
  • 15,682
  • 4
  • 47
  • 63