M Raymaker
M Raymaker

Reputation: 1271

How to catch exceptions in SendMailAsync method

I have a C# wcf Windows service in .net 4.5 that sends emails to about 1000 different customers daily. I would like to try sending the emails async using this snippet of code I found here on SO, but how should I wrap it to catch exceptions?

public async Task SendAsync(string subject, string body, string recipient)
{
    var mailMessage = new MailMessage("[email protected]", recipient, subject, body);
    mailMessage.IsBodyHtml = true;

    using(var client = new SmtpClient("mysmtpserver"))
    {
        try
        {
            await client.SendMailAsync(mailMessage);
        }
        catch (Exception ex)
        {
           // Log here
        }
    }
}

I'm expecting exceptions from invalid e-mail adresses and server timeouts.

Should I just wrap the await Call in a try-catch? Not sure this will work.

Also where is the best place to put the foreach loop that runs through all mail adresses?

Thanks.

Upvotes: 4

Views: 4370

Answers (2)

Christian4423
Christian4423

Reputation: 1796

I know that this is a old post and it is answered already but I am able to catch await calls using this method.

public async Task < JsonResult > UserDelete(string username) {
  // return obj
  MFFCommon retval = new MFFCommon();

  // get user
  var user = UserManager.FindByName(username);
  
  // starts a task
  Task removeUserFromAgency = await Task.Factory.StartNew(async() => {
    await removeUserFromCurrentAgency(user);
  });
  
  // optional, but this will wait 3 sec before checking if it is complete.
  removeUserFromAgency.Wait(3000);
  
  
  if (removeUserFromAgency.IsCompleted) {
    retval.taskResponse = "True";
    retval.taskError = null;
    return Json(retval, JsonRequestBehavior.AllowGet);
  } else {
    // This is where the exception is at.
    retval.taskResponse = "False";
    retval.taskError = removeUserFromAgency.Exception.Message;
    return Json(retval, JsonRequestBehavior.AllowGet);
  }
}

Upvotes: 1

usr
usr

Reputation: 171188

Should I just wrap the await Call in a try-catch? Not sure this will work.

Yes, await propagates exceptions and this will work. Of course, many mail delivery failures occur after the mail has left your servers and you get a bounce back or even nothing. This is not detectable no matter how you send the mail.

Also where is the best place to put the foreach loop that runs through all mail addresses?

Not sure what you mean. Place the loop around a call to SendAsync? Where else could it go? I probably misunderstand.

Upvotes: 4

Related Questions