Friday, January 22, 2010

Sending Email from asp.net with proper exception handling

Hi below is the code for sending email from asp.net application......


using System.Net;
using System.Net.Mail;

public MailGeneration()
        {           
           
            StringBuilder sb = new StringBuilder();
            sb.Append("Hello "+"<br/>");
            sb.Append("Please find the occupations report attached to this mail.");
            sb.Append("<br/><br/>");
            sb.Append("Warm Regards,");           
            string strBd = sb.ToString();
            strBd = HttpContext.Current.Server.HtmlDecode(strBd);

            MailMessage mail = new MailMessage("Hara@Testmail.com", "mail@testmail.com");//sends to candidate
           
            mail.CC.Add("mail@ccmail.com");//sends as CC
            mail.Subject = "Mail Subject";
           
            mail.Body = "Mail Body";
            mail.IsBodyHtml = true;

            mail.Attachments.Add(new System.Net.Mail.Attachment("File to be attached"));           
            mail.Attachments[0].Name = "File Name to be Displayed";

            string smtpClient = System.Configuration.ConfigurationManager.AppSettings["SMTPClientHost"].ToString().Trim();

            SmtpClient objSmtpClient = new SmtpClient(smtpClient);

            try
            {
                objSmtpClient.Send(mail); //Sending Mail
            }
            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;

                    if ((statusCode == System.Net.Mail.SmtpStatusCode.MailboxBusy) || (statusCode == System.Net.Mail.SmtpStatusCode.MailboxUnavailable))
                    {
                        //Log this to event log: recExc.InnerExceptions[recipient].FailedRecipient
                        System.Threading.Thread.Sleep(5000);
                        objSmtpClient.Send(mail);
                    }
                    else
                    {
                        //Log error to event log.
                        //recExc.InnerExceptions[recipient].StatusCode or use statusCode
                    }

                }
            }
            //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.               
            }
            finally
            {
                mail.Attachments.Dispose();              
            }

        }

No comments:

Post a Comment