Thursday, December 3, 2015

Email Helper in C# - A Common & Easy Way of Sending Emails

Most of the time, it is common to send emails through the application which some may related to technical or error handling and sometimes to customers which could be even internal or external. Such cases, SmtpClient is the class we use in ASP.Net

Using a bit of OOP can help to have a common way of sending emails and can be widely used across the application. Below is an example of an Email helper class which can be used widely. 

 public class EmailHelper  
   {  
     private MailMessage Message = null;  
     private SmtpClient smtpClient = null;  
     public MailAddress FromAddress { get; set; }  
     public string Subject { get; set; }  
     public string Body { get; set; }  
     public EmailHelper()  
     {  
       smtpClient = new SmtpClient();  
       smtpClient.Host = ConfigurationManager.AppSettings["smtpHost"];  //Configure as your email provider
       smtpClient.UseDefaultCredentials = false;  
       //smtpClient.EnableSsl = true;//comment if you don't need SSL  
       smtpClient.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["userName"], ConfigurationManager.AppSettings["password"]);  
       smtpClient.Port = Convert.ToInt32(ConfigurationManager.AppSettings["port"]);  
       Message = new MailMessage();  
     }  
     public EmailHelper(string host, int port, string userName, string password, bool ssl)  
       : this()  
     {  
       smtpClient.Host = host;  
       smtpClient.Port = port;  
       smtpClient.EnableSsl = ssl;  
       smtpClient.Credentials = new NetworkCredential(userName, password);  
     }  
     public void AddToAddress(string email, string name = null)  
     {  
       if (!string.IsNullOrEmpty(email))  
       {  
         email = email.Replace(",", ";");  
         string[] emailList = email.Split(';');  
         for (int i = 0; i < emailList.Length; i++)  
         {  
           if (!string.IsNullOrEmpty(emailList[i]))  
             Message.To.Add(new MailAddress(emailList[i], name));  
         }  
       }  
     }  
     public void AddCcAddress(string email, string name = null)  
     {  
       if (!string.IsNullOrEmpty(email))  
       {  
         email = email.Replace(",", ";");  
         string[] emailList = email.Split(';');  
         for (int i = 0; i < emailList.Length; i++)  
         {  
           if (!string.IsNullOrEmpty(emailList[i]))  
             Message.CC.Add(new MailAddress(emailList[i], name));  
         }  
       }  
     }  
     public void AddBccAddress(string email, string name = null)  
     {  
       if (!string.IsNullOrEmpty(email))  
       {  
         email = email.Replace(",", ";");  
         string[] emailList = email.Split(';');  
         for (int i = 0; i < emailList.Length; i++)  
         {  
           if (!string.IsNullOrEmpty(emailList[i]))  
             Message.Bcc.Add(new MailAddress(emailList[i], name));  
         }  
       }  
     }  
     public void AddAttachment(string file, string mimeType)  
     {  
       Attachment attachment = new Attachment(file, mimeType);  
       Message.Attachments.Add(attachment);  
     }  
     public void AddAttachment(Attachment objAttachment)  
     {  
       Message.Attachments.Add(objAttachment);  
     }  
     public void SendMail()  
     {  
       if (FromAddress == null || (FromAddress != null && FromAddress.Address.Equals("")))  
       {  
         throw new Exception("From address not defined");  
       }  
       else  
       {  
         if (string.IsNullOrEmpty(FromAddress.DisplayName))  
           FromAddress = new MailAddress(FromAddress.Address, string.Empty);  
         Message.From = FromAddress;  
       }  
       if (Message.To.Count <= 0)  
       { throw new Exception("To address not defined"); }  
       Message.Subject = Subject;  
       Message.IsBodyHtml = true;  
       Message.Body = Body;  
       smtpClient.Send(Message);  
     }  
     public static string GetFileMimeType(string fileName)  
     {  
       string fileExt = Path.GetExtension(fileName.ToLower());  
       string mimeType = string.Empty;  
       switch (fileExt)  
       {  
         case ".htm":  
         case ".html":  
           mimeType = "text/html";  
           break;  
         case ".xml":  
           mimeType = "text/xml";  
           break;  
         case ".jpg":  
         case ".jpeg":  
           mimeType = "image/jpeg";  
           break;  
         case ".gif":  
           mimeType = "image/gif";  
           break;  
         case ".png":  
           mimeType = "image/png";  
           break;  
         case ".bmp":  
           mimeType = "image/bmp";  
           break;  
         case ".pdf":  
           mimeType = "application/pdf";  
           break;  
         case ".doc":  
           mimeType = "application/msword";  
           break;  
         case ".docx":  
           mimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";  
           break;  
         case ".xls":  
           mimeType = "application/x-msexcel";  
           break;  
         case ".xlsx":  
           mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";  
           break;  
         case ".csv":  
           mimeType = "application/csv";  
           break;  
         case ".ppt":  
           mimeType = "application/vnd.ms-powerpoint";  
           break;  
         case ".pptx":  
           mimeType = "application/vnd.openxmlformats-officedocument.presentationml.presentation";  
           break;  
         case ".rar":  
           mimeType = "application/x-rar-compressed";  
           break;  
         case ".zip":  
           mimeType = "application/x-zip-compressed";  
           break;  
         default:  
           mimeType = "text/plain";  
           break;  
       }  
       return mimeType;  
     }  
   }  
 }  

This class can be used as follows,

 StringBuilder fileNames = new StringBuilder();  
 string strPath = string.Empty;  
 string coType = IPODMT.common.IQuestConst.MessageStatus.Sent;  
 string url = string.Empty;  
 EmailHelper emailHelper = new EmailHelper();  
 emailHelper.FromAddress = new System.Net.Mail.MailAddress(hdnFromAddress.Value.Trim());  
 emailHelper.AddToAddress(txtEmailTo.Text.Trim());  
 emailHelper.AddCcAddress(txtEmailCc.Text.Trim());  
 emailHelper.AddBccAddress(txtEmailBcc.Text.Trim());  
 Dictionary<int, KeyValuePair<string, string>> fileList = null;  
 //Attaching files. Here I keep the values in a session
 fileList = (Dictionary<int, KeyValuePair<string, string>>)Session["UploadedFileList"];  
 foreach (var item in fileList)  
 {  
     emailHelper.AddAttachment(item.Value.Key + item.Value.Value, EmailHelper.GetFileMimeType(item.Value.Value));  
     FileInfo file = new FileInfo(item.Value.Key + item.Value.Value);  
     fileNames.Append(item.Value.Value + "|" + file.Length.ToString() + ";");  
 }  
 string strAttachment = hdnAttachmentTemplate.Value;  
 string msgBody = string.Empty;  
 try  
 {  
     emailHelper.Subject = txtEmailSubject.Text.Trim();  
     if (!string.IsNullOrEmpty(strAttachment) && fileList != null && fileList.Count > 0)  
     {  
         strAttachment = strAttachment.Replace("[flAttachment]", fileList.Count.ToString());  
         msgBody = txtEmailBody.InnerText.Trim() + "<br/>" + strAttachment;  
     }  
     else  
         msgBody = txtEmailBody.InnerText.Trim();// +"<br/>" + txtCustomerInfo.Text.Trim();  
 msgBody = msgBody.Replace("[lbCustomerInfo]", txtCustomerInfo.Text.Trim());  
 emailHelper.Body = msgBody;  
 emailHelper.SendMail();  //After sending email you can clear the session "UploadedFileList"
 }  
 catch (Exception)  
     {  
         //Handle your errors. May be a server log file? Its up to you!
     }  

Copy this code and paste it in your project. Remember to apply the correct SMTPClient settings as per your email provider.

Happy coding.. :)

No comments:

Post a Comment