title: ASP.Net C# - Catching errors when sending an email
body: <p>So I've got a function to send an email which I run within a button click event after some validation.  However, how do I catch any errors when sending an email?  I'm familiar with the try-catch-finally approach so would the code at the bottom be sufficient?</p>
  
  <pre><code>protected void sendEmail(string activationCode, string username, string emailAddress)
  {
      SmtpClient SmtpServer = new SmtpClient("smtp.live.com");
      var mail = new MailMessage();
      mail.From = new MailAddress("EMAIL");
      mail.To.Add(emailAddress);
      mail.Subject = "Please activate your account.";
      mail.IsBodyHtml = true;
      string htmlBody;
      htmlBody = "Dear " + username + "&lt;br /&gt;&lt;br /&gt;";
      htmlBody += "Thank you for registering an account.  Please activate your account by visiting the URL below:&lt;br /&gt;&lt;br /&gt;";
      htmlBody += "http://localhost:57167/signin.aspx?activate=" + activationCode + "&lt;br /&gt;&lt;br /&gt;";
      htmlBody += "Thank you.";
      mail.Body = htmlBody;
      SmtpServer.Port = 587;
      SmtpServer.UseDefaultCredentials = false;
      SmtpServer.Credentials = new System.Net.NetworkCredential("EMAIL", "PASSWORD");
      SmtpServer.EnableSsl = true;
      SmtpServer.Send(mail);
  }
  </code></pre>
  
  <p>Is something like this okay?</p>
  
  <pre><code>protected void sendEmail(string activationCode, string username, string emailAddress)
  {
      try
      {
      SmtpClient SmtpServer = new SmtpClient("smtp.live.com");
      var mail = new MailMessage();
      mail.From = new MailAddress("EMAIL");
      mail.To.Add(emailAddress);
      mail.Subject = "Please activate your account.";
      mail.IsBodyHtml = true;
      string htmlBody;
      htmlBody = "Dear " + username + "&lt;br /&gt;&lt;br /&gt;";
      htmlBody += "Thank you for registering an account.  Please activate your account by visiting the URL below:&lt;br /&gt;&lt;br /&gt;";
      htmlBody += "http://localhost:57167/signin.aspx?activate=" + activationCode + "&lt;br /&gt;&lt;br /&gt;";
      htmlBody += "Thank you.";
      mail.Body = htmlBody;
      SmtpServer.Port = 587;
      SmtpServer.UseDefaultCredentials = false;
      SmtpServer.Credentials = new System.Net.NetworkCredential("EMAIL", "PASSWORD");
      SmtpServer.EnableSsl = true;
      SmtpServer.Send(mail);
      }
      catch
      {
          lblError.Text = "error message";
      }
  }
      }
  </code></pre>