For training related to .net,OOPS,design patterns, MVC,WCF and .net fundamentals
contact at sukeshmarla@gmail.com or Click Here

Click here for my training feedbacks

Followers

Follow Us



Share your Interview questions here


For software development queries contact SukeshMarla@Gmail.com

Follow by Email

Learn everything about JSON in a day

28 April 2011

Sending Emails using .net

For sending email
1. You need SMTP Server to communicate with, as well you must be able to properly authenticate with this server.
Following class encapsulate all the setting required to authenticate with the server.
namespace SukeshMarlaBlogs
{
    public class ClsSmtpSettings
    {
        public string User { get; set; }
        public string Password { get; set; }
        public string Server { get; set; }
        public int Port { get; set; }
        public bool RequiresAuthentication { get; set; }
        public bool EnableSSl { get; set; }
        public string PreferredEncoding { get; set; }
        public bool IsValid
        {
            get
            {
                if (Server.Length == 0) { return false; }

                if (RequiresAuthentication)
                {
                    if (User.Length == 0) { return false; }
                    if (Password.Length == 0) { return false; }
                }

                return true;
            }
        }
    }
}
2. A Class which will encapsulate all the message parts
namespace SukeshMarlaBlogs
{
    public class ClsMailParts
    {
     
        public string StrFrom { get; set; }
        public string StrReplyTo { get; set; }
        public string StrTo { get; set; }
        public string StrCC { get; set; }
        public string StrBcc { get; set; }
        public string StrSubject { get; set; }
        public string StrMessageBody { get; set; }
        public bool IsBodyHtml { get; set; }
        public MailPriority ObjPriEmailPriority { get; set; }
        public List<ClsAttachment> ObjPriAttachments { get; set; }
    }
}
3. A Class For Attachments
namespace SukeshMarlaBlogs
{
    public class ClsAttachment
    {
        public string StrAttachmentName{get;set;}
        public string StrAttachmentPath{get;set;}
    }
}
4. A Class For Actually Sending the Email
namespace SukeshMarlaBlogs
{
    public class ClsEmail
    {
        public void SendEmail(ClsSmtpSettings ObjSmtpSettings, ClsMailParts ObjPriMailParts)
        {
            if ((ObjSmtpSettings == null) || (!ObjSmtpSettings.IsValid))
            {
                throw new Exception("Invalid smtp settings detected in SendEmail ");
            }

            MailMessage ObjMail = new MailMessage();
            MailAddress ObjFromAddress = new MailAddress(ObjPriMailParts.StrFrom);
            MailAddress ObjToAddress = new MailAddress(ObjPriMailParts.StrTo);
            ObjMail.From = ObjFromAddress;
            ObjMail.To.Add(ObjToAddress);

            if (ObjPriMailParts.StrReplyTo.Length > 0)
            {
                MailAddress ObjReplyAddress = new MailAddress(ObjPriMailParts.StrReplyTo);
                ObjMail.ReplyTo = ObjReplyAddress;
            }

            if (ObjPriMailParts.StrCC.Length > 0)
            {
                MailAddress ObjCCAddress = new MailAddress(ObjPriMailParts.StrCC);
                ObjMail.CC.Add(ObjCCAddress);
            }

            if (ObjPriMailParts.StrBcc.Length > 0)
            {
                MailAddress ObjBccAddress = new MailAddress(ObjPriMailParts.StrBcc);
                ObjMail.Bcc.Add(ObjBccAddress);
            }

            ObjMail.Subject = ObjPriMailParts.StrSubject;
            ObjMail.Priority = ObjPriMailParts.ObjPriEmailPriority;
            ObjMail.Body = ObjPriMailParts.StrMessageBody;

            if (ObjPriMailParts.IsBodyHtml)
            {
                ObjMail.IsBodyHtml = true;
            }

            SmtpClient ObjSmtpCLient = new SmtpClient(ObjSmtpSettings.Server, ObjSmtpSettings.Port);
            ObjSmtpCLient.EnableSsl = ObjSmtpSettings.EnableSSl;

            if (ObjSmtpSettings.RequiresAuthentication)
            {
                NetworkCredential smtpCredential
                = new NetworkCredential(
                ObjSmtpSettings.User,
                ObjSmtpSettings.Password);

                ObjSmtpCLient.Credentials = smtpCredential;
            }

            // add attachments if there are any
            if (ObjPriMailParts.ObjPriAttachments!=null && ObjPriMailParts.ObjPriAttachments.Count > 0)
            {
                for (int i = 0; i < ObjPriMailParts.ObjPriAttachments.Count; i++)
                {
                    if (!File.Exists(ObjPriMailParts.ObjPriAttachments[i].StrAttachmentPath))
                    {
                        throw new Exception("could not find file for email attachment " +
                            ObjPriMailParts.ObjPriAttachments[i].StrAttachmentPath);
                    }

                    Attachment ObjPriAttachment = new Attachment(ObjPriMailParts.ObjPriAttachments[i].StrAttachmentPath);
                    ObjPriAttachment.Name = ObjPriMailParts.ObjPriAttachments[i].StrAttachmentName;
                    ObjMail.Attachments.Add(ObjPriAttachment);
                }
            }

            try
            {
                ObjSmtpCLient.Send(ObjMail);
            }
            catch (SmtpException ex)
            {
                throw new Exception("error sending email to " + ObjPriMailParts.StrTo + ", message was: " + ObjPriMailParts.StrMessageBody, ex);

            }
            catch (SocketException ex)
            {
                throw new Exception("error sending email to " + ObjPriMailParts.StrTo + ", message was: " + ObjPriMailParts.StrMessageBody, ex);
            }

        }
    }
}
Now to Test the Code we need following code Block (Just replace the settings according to your convenience)
    
    SukeshMarlaBlogs.ClsSmtpSettings ObjPriSmtp = new SukeshMarlaBlogs.ClsSmtpSettings();
    ObjPriSmtp.Server = "mail.somewhere.com";
    ObjPriSmtp.User = "someone@somewhere.com";
    ObjPriSmtp.RequiresAuthentication = true;
    ObjPriSmtp.Password = "pasword";
    ObjPriSmtp.Port = 85;
            

    SukeshMarlaBlogs.ClsMailParts ObjPriMailParts = new SukeshMarlaBlogs.ClsMailParts();
    ObjPriMailParts.IsBodyHtml = false;
    ObjPriMailParts.ObjPriAttachments = null;
    ObjPriMailParts.ObjPriEmailPriority = MailPriority.High;
    ObjPriMailParts.StrBcc = string.Empty;
    ObjPriMailParts.StrCC = string.Empty;              
    ObjPriMailParts.StrFrom = "Sukesh@Marla.com";
    ObjPriMailParts.StrMessageBody = "Welcome To Sukesh Marla's World";
    ObjPriMailParts.StrReplyTo = string.Empty;
    ObjPriMailParts.StrSubject = "Test Message";
    ObjPriMailParts.StrTo = "Tester@Blogspot.com";


    SukeshMarlaBlogs.ClsEmail ObjPriEmail = new SukeshMarlaBlogs.ClsEmail();
    ObjPriEmail.SendEmail(ObjPriSmtp, ObjPriMailParts);