ASP.NET MVC: How to Send Email with Example

Updated on     Kisan Patel

In this tutorial, I will explain how to send an email in ASP.NET MVC.

To Send an email you need to configure an SMTP server, port, username, and password. To allow for easy configuration, I would suggest placing these in the appSetting of your Web.config file:

<appSettings>
   <add key="webpages:Version" value="1.0.0.0" />
   <add key="ClientValidationEnabled" value="true" />
   <add key="UnobtrusiveJavaScriptEnabled" value="true" />
   <add key="smtpServer" value="localhost" />
   <add key="smtpPort" value="25" />
   <add key="smtpUser" value="" />
   <add key="smtpPass" value="" />
   <add key="adminEmail" value="no-reply@no-reply.com" />
</appSettings>

In above code, you need to change values as necessary to reflect your SMTP server, port, username, and password.

Now, I will create a static MailClient class to provide easy access to the class and its functions as seen in below code. When you can integrate MailClient class it won’t require instantiating new objects.
code

The MailClient class begins by instantiating a new SmtpClient variable with the settings defined from the Web.config.

Next a SendMessage function is created. This function is private and should not be called directly from outside of this class. This function is what performs the actual sending. It creates a new MailMessage object and sends it through the SmtpClient object created earlier.

Finally, a SendEmail function is created that accepts the users email address, subject and body. It generates a generic message that should be updated to send your email and it is sent by calling the SendEmail function.

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

namespace MvcEmailDemo
{
    public static class MailClient
    {
        private static readonly SmtpClient Client;

        static MailClient()
        {
            Client = new SmtpClient
            {
                Host = ConfigurationManager.AppSettings["SmtpServer"],
                Port = Convert.ToInt32(ConfigurationManager.AppSettings["SmtpPort"]),
                DeliveryMethod = SmtpDeliveryMethod.Network
            };
            Client.UseDefaultCredentials = false;
            Client.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["SmtpUser"], ConfigurationManager.AppSettings["SmtpPass"]);
        }

        private static bool SendMessage(string from, string to, string subject, string body)
            {
                MailMessage mm = null;
                bool isSent = false;
                try
                {
                    // Create our message
                    mm = new MailMessage(from, to, subject, body);
                    mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
                    // Send it
                    Client.Send(mm);
                    isSent = true;
                }
                // Catch any errors, these should be logged and
                // dealt with later
                catch (Exception ex)
                {
                    // If you wish to log email errors,
                    // add it here...
                    var exMsg = ex.Message;
                }
                finally
                {
                    mm.Dispose();
                }
                return isSent;
        }

        public static bool SendEmail(string email, string subject, string body)
        {
            return SendMessage(ConfigurationManager.AppSettings["adminEmail"], email, subject, body);
        }
    }
}

To actually send the email just call the SendEmail function directly from controller as seen in below code:

public class HomeController : Controller
{
    //
    // GET: /Home/

    public ActionResult Index()
    {
        // Send email
        MailClient.SendEmail("", "Subject Title", "Message Body");
        return View();
    }

}

Download Complement Source Code


ASP.NET MVC

Leave a Reply