Thursday, November 29, 2012

Email Sending method


using System.Net.Mail;
private void SendEmails(string to, string from, string cc, string bcc, string subject, string message, string smtpAddress)
        {
            try
            {
 
                char emailSeperator = Convert.ToChar(',');
                WriteLog("From:" + from);
                WriteLog("To:" + to);
                WriteLog("CC:" + cc);
                WriteLog("BCC:" + bcc);
                MailMessage msgMail = new MailMessage();
                string[] arrToEmail = to.Split(emailSeperator);
                foreach (string toEmail in arrToEmail)
                {
                    msgMail.To.Add(toEmail);
                }
                if (!string.IsNullOrEmpty(cc.Trim()))
                {
                    string[] arrCCEmail = cc.Split(emailSeperator);
                    foreach (string ccEmail in arrCCEmail)
                    {
                        msgMail.CC.Add(ccEmail);
                    }
 
                }
                if (!string.IsNullOrEmpty(bcc.Trim()))
                {
                    string[] arrBCCEmail = bcc.Split(emailSeperator);
                    foreach (string bccEmail in arrBCCEmail)
                    {
                        msgMail.Bcc.Add(bccEmail);
                    }
 
                }
                msgMail.IsBodyHtml = true;
                msgMail.From = new MailAddress(from);
                msgMail.Subject = subject;
                msgMail.Body = message;
                SmtpClient SmtpSend = new SmtpClient(smtpAddress);
                try
                {
                    SmtpSend.Send(msgMail);
                    WriteLog("***************************");
                    WriteLog("Email sent to : " + to + " , Email sent from : " + from + " , Subject : " + subject);
                    WriteLog("***************************");
                }
                catch (Exception ex)
                {
                    LogMessage(ex);
                }
            }
            catch (Exception ex)
            {
                LogMessage(ex);
            }
 
        }

No comments:

Post a Comment