Click here to Skip to main content
15,867,835 members
Articles / Web Development / ASP.NET

Mail Helper for Sending Emails in ASP.NET MVC using C#

Rate me:
Please Sign up or sign in to vote.
3.67/5 (4 votes)
9 Feb 2015CPOL 35.3K   11   3
In this post, we will create a simple mail helper class for sending emails in ASP.NET MVC using C#.

In this post, we will create a simple mail helper class for sending emails in ASP.NET MVC using C#.

Implementation

Create a class named MailHelper and then add the following code.

Mail Helper

C#
public class MailHelper
    {
        private const int Timeout = 180000;
        private readonly string _host;
        private readonly int _port;
        private readonly string _user;
        private readonly string _pass;
        private readonly bool _ssl;

        public string Sender { get; set; }
        public string Recipient { get; set; }
        public string RecipientCC { get; set; }
        public string Subject { get; set; }
        public string Body { get; set; }
        public string AttachmentFile { get; set; }

        public MailHelper()
        {
            //MailServer - Represents the SMTP Server
            _host = ConfigurationManager.AppSettings["MailServer"];
            //Port- Represents the port number
            _port = int.Parse(ConfigurationManager.AppSettings["Port"]);
            //MailAuthUser and MailAuthPass - Used for Authentication for sending email
            _user = ConfigurationManager.AppSettings["MailAuthUser"];
            _pass = ConfigurationManager.AppSettings["MailAuthPass"];
            _ssl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSSL"]);
        }

        public void Send()
        {
            try
            {
                // We do not catch the error here... let it pass direct to the caller
                Attachment att = null;
                var message = new MailMessage(Sender, Recipient, Subject, Body) { IsBodyHtml = true };
                if (RecipientCC != null)
                {
                    message.Bcc.Add(RecipientCC);
                }
                var smtp = new SmtpClient(_host, _port);

                if (!String.IsNullOrEmpty(AttachmentFile))
                {
                    if (File.Exists(AttachmentFile))
                    {
                        att = new Attachment(AttachmentFile);
                        message.Attachments.Add(att);
                    }
                }

                if (_user.Length > 0 && _pass.Length > 0)
                {
                    smtp.UseDefaultCredentials = false;
                    smtp.Credentials = new NetworkCredential(_user, _pass);
                    smtp.EnableSsl = _ssl;
                }

                smtp.Send(message);

                if (att != null)
                    att.Dispose();
                message.Dispose();
                smtp.Dispose();
            }

            catch (Exception ex)
            {

            }
        }
    }

Place the following code in the app settings of your application:

ASP.NET
<appSettings>
<add key="MailServer" value="smtp.gmail.com"/>
<add key="Port" value="587″/>
<add key="EnableSSL" value="true"/>
<add key="EmailFromAddress" value="xxxx@gmail.com"/>
<add key="MailAuthUser" value="xxxx@gmail.com"/>
<add key="MailAuthPass" value="xxxxxxxx"/>
</appSettings>

If you don’t have authentication for sending emails, you can pass the empty string in MailAuthUser and MailAuthPass.

ASP.NET
<appSettings>
<add key="MailServer" value="smtp.gmail.com"/>
<add key="Port" value="587"/>
<add key="EnableSSL" value="true"/>
<add key="EmailFromAddress" value="xxxx@gmail.com"/>
<add key="MailAuthUser" value=""/>
<add key="MailAuthPass" value=""/>
</appSettings>

Usage

Add the following code snippet in your controller to call MailHelper class for sending emails.

JavaScript
var MailHelper = new MailHelper
   {
      Sender = sender, //email.Sender,
      Recipient = useremail,
      RecipientCC = null,
      Subject = emailSubject,
      Body = messageBody
   };
 MailHelper.Send();

The post Mail Helper for sending emails in ASP.NET MVC using C# appeared first on Venkat Baggu Blog.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) eBiz Solutions http://venkatbaggu.com/
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionThank you! Pin
xkryon12-Aug-15 11:23
xkryon12-Aug-15 11:23 
GeneralMy vote of 1 Pin
maxnis11-Feb-15 14:45
maxnis11-Feb-15 14:45 
QuestionA better way of using the configuration file Pin
King-----Kong10-Feb-15 14:51
King-----Kong10-Feb-15 14:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.