Scenario:
Sending email is one of the most common requirement and it usually works great in DEV environment because Mail Server is usually not locked down. But you never know the rules set up in Production.
Solution:
Robust Error handling is the answer to most production issues.Here's a modified version of the robust email solution in ASP.net
Code:
private void SendMail(string from, string to , string subject, string body)Article:
{
//Create message object and populate w/ data from form
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.From = new System.Net.Mail.MailAddress(from);
message.To.Add(to);
message.Subject = subject;
message.Body = body;
//Setup SmtpClient to send email. Uses web.config settings.
System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();
//Error handling for sending message
try
{
smtpClient.Send(message);
}
catch (System.Net.Mail.SmtpFailedRecipientsException recExc)
{
for (int recipient = 0; recipient < recExc.InnerExceptions.Length - 1; recipient++)
{
System.Net.Mail.SmtpStatusCode statusCode;
//Each InnerException is an System.Net.Mail.SmtpFailed RecipientException
statusCode = recExc.InnerExceptions[recipient].StatusCode;
//Log error to event log.
}
}
//General SMTP execptions
catch (System.Net.Mail.SmtpException smtpExc)
{
//Log error to event log using StatusCode information in
//smtpExc.StatusCode
}
catch (Exception ex)
{
//Log error to event log.
}
}
SmtpFailedRecipientsException , SmtpException
Follow me on Twitter
0 comments:
Post a Comment