Well, you have the entire body of code wrapped in a try
block with an empty catch
block. So, if the message fails to send for whatever reason, you will have no idea because your function will simply return.
If you look at the MSDN documentation for SmtpClient.Send you'll see that there are a number of different exceptions it can throw for various reasons. A couple interesting ones:
- SmtpException
- SmtpFailedRecipientsException
A couple of notes after your update:
You probably don't mean to do this:
mailclient.Send(mail);
mailclient.Dispose();
try
{
mailclient.Send(mail);
mailclient.Dispose();
}
You're disposing mailclient
before trying to use it again.
using
MailMessage
and SmtpClient
both implement IDisposable, so it would be best practice (and easiest) to put them in a using block:
using (var mail = new MailMessage())
using (var mailclient = new SmtpClient())
{
// ...
}
Then you won't have to worry about calling Dispose()
in your finally
blocks (you may not need them at all then).
throw
You're probably aware, but there's no point in:
catch (Exception ex)
{
throw ex;
}
foreach
for (int i = 0; i < ex.InnerExceptions.Length; i++)
{
SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;
// ...
}
Can be re-written as:
foreach (var innerEx in ex.InnerExceptions)
{
var status = innerEx.StatusCode;
}
Thread.Sleep()
If this code is user-facing, you probably don't really want to do this, as it is going to cause the page to hang for 5 seconds waiting to send. In my opinion, you shouldn't handle sending mail directly in the web page code anyway, you should queue it up for a background task to send. But that's an entirely different issue.
Just a few things to help make you a better C# coder.