In this article I will explain with an example, how to send email using JavaScript XmlHttpRequest (XHR) and AJAX in ASP.Net MVC.
The JavaScript XmlHttpRequest (XHR) function will call a Web API Action method which will send email using Gmail SMTP Mail Server in ASP.Net MVC.
Note: For beginners in ASP.Net MVC and Web API, please refer my article: What is Web API, why to use it and how to use it in ASP.Net MVC
 
 

Mail Server Settings in Web.Config file

The following Mail Server settings need to be saved in the Web.Config file.
Note: It is necessary to use the sender’s email address credentials while defining the Gmail SMTP Server Credentials as Gmail the sender’s email address must be same as the Gmail Username specified in credentials.
 
<system.net>
    <mailSettings>
        <smtp deliveryMethod"Network" from"sender@gmail.com">
            <network
                host="smtp.gmail.com"
                port="587"
                enableSsl="true"
                userName="sender@gmail.com"
                password="GMAILor2STEP-PASSWORD"
                defaultCredentials"true"/>
        </smtp>
    </mailSettings>
</system.net>
 
 

Sending Email using jQuery AJAX

MailMessage class properties

Following are the required properties of the MailMessage class.
From – Sender’s email address.
To – Recipient(s) Email Address.
CC – Carbon Copies (if any).
BCC – Blind Carbon Copies (if any).
Subject – Subject of the Email.
Body – Body of the Email.
IsBodyHtml – Specify whether body contains text or HTML mark up.
Attachments – Attachments (if any).
ReplyTo – ReplyTo Email address.
 

SMTP class properties

Following are the properties of the SmtpClient class.
Host – SMTP Server URL (Gmail: smtp.gmail.com).
EnableSsl – Specify whether your host accepts SSL Connections (Gmail: True).
UseDefaultCredentials – Set to True in order to allow authentication based on the Credentials of the Account used to send emails.
Credentials – Valid login credentials for the SMTP server (Gmail: email address and password).
Port – Port Number of the SMTP server (Gmail: 587).
 
 

Model

The Model class consists of following properties.
public class EmailModel
{
    public string Email{ get;set; }
    public string Subject{ get;set; }
    public string Body{ get;set; }
}
 
 

Namespaces

You will need to import the following namespaces.
using System.Net;
using System.Net.Mail;
using System.Net.Configuration;
using System.Configuration;
 
 

Controller

The Controller consists of following Action method.

Action method for handling GET operation

Inside this Action method, simply the View is returned.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }
}
 
 

Web API Controller

The Web API Controller consists of following Action method.

Action method for Sending Email

This Action method handles the POST call made from the JavaScript XmlHttpRequest (XHR) function.
Inside this Action method, the Sender email address (from) is fetched from the SmtpSection of the Web.Config file and the values of Subject and Body are fetched from their respective properties of EmailModel class object.
 

Setting Body of Email

The IsBodyHtml property of MailMessage class is set to TRUE.
Then, object of the SmtpClient class is created and the settings of the Mail Server such as Host, Port, EnableSsl, Username and Password are fetched from the mailSettings section of the Web.Config file and are set in respective properties of the SmtpClient class object.
Finally, an email is sent using Send method of the SmtpClient class and a Success Message displayed using JavaScript Alert Message Box.
public class AjaxAPIController : ApiController
{
    [Route("api/AjaxAPI/SendEmail")]
    [HttpPost]
    public string SendEmail(EmailModel email)
    {
        //Read SMTP section from Web.Config.
        SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
 
        using (MailMessage mm = new MailMessage(smtpSection.From,email.Email))
        {
            mm.Subject  email.Subject;
            mm.Body  email.Body;
            mm.IsBodyHtml =  true;
 
            using (SmtpClient smtp = new SmtpClient())
            {
                smtp.Host smtpSection.Network.Host;
                smtp.EnableSsl smtpSection.Network.EnableSsl;
                NetworkCredential networkCred = new NetworkCredential(smtpSection.Network.UserName, smtpSection.Network.Password);
                smtp.UseDefaultCredentials = true;
                smtp.Credentials = networkCred;
                smtp.Port smtpSection.Network.Port;
                smtp.Send(mm);
            }
        }
 
        return "Email sentsuccessfully.";
    }
}
 
 

View

HTML Markup

The View consists of two TextBoxes, a TextArea and a Button.
The Button has been assigned with a JavaScript click event handler.
 

Submitting the Form

When the Send button is clicked, the TextBoxes and TextArea values are passed to the SendEmail Action method of Web API using JavaScript XmlHttpRequest (XHR) function.
Note: For more details on calling Web API using JavaScript XmlHttpRequest (XHR) function in ASP.Net MVC, please refer my article ASP.Net MVC: Call (Consume) Web API using JavaScript and AJAX.
 
Finally, the received Success Message is displayed using JavaScript Alert Message Box.
@{
     Layout =  null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <table border="0" cellpadding="0" cellspacing="0">
        <tr>
            <td>To:</td>
            <td><input type="text" id="txtEmail" /></td>
        </tr>
        <tr>
            <td>Subject:</td>
            <td><input type="text" id="txtSubject" /></td>
        </tr>
        <tr>
            <td valign="top">Body:</td>
            <td><textarea id="txtBody" rows="3" cols="20"></textarea></td>
        </tr>
        <tr>
            <td></td>
            <td><input type="button" id="btnSend" value="Send" /></td>
        </tr>
    </table>
    <script type="text/javascript">
        function SendEmail() {
 
            var to = document.getElementById("txtEmail").value;
            var subject = document.getElementById("txtSubject").value;
            var body = document.getElementById("txtBody").value;
            var email = '{Email: "'  + to +'", Subject: "'  + subject +'", Body: "'  + body +'" }';
 
            var request;
            if (window.XMLHttpRequest) {
                //New browsers.
                 request =  new XMLHttpRequest();
            }
            else if (window.ActiveXObject) {
                //Old IE Browsers.
                 request =  new ActiveXObject("Microsoft.XMLHTTP");
            }
            if (request !=  null) {
                var url  "/api/AjaxAPI/SendEmail";
                request.open("POST"urlfalse);
                var params = email;
                request.setRequestHeader("Content-Type","application/json");
                request.onreadystatechange  =  function () {
                    if (request.readyState  == 4 &&request.status == 200) {
                        var  response = JSON.parse(request.responseText);
                        alert(response);
                    }
                };
                request.send(params);
            }
        };
    </script>
</body>
</html>
 
 

Possible Errors

The following error occurs when you try to send email using Gmail credentials in your application.
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details:System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at
 

Solution

 
 

Screenshots

Email Form

ASP.Net MVC: Send Email using JavaScript
 

Received Email

ASP.Net MVC: Send Email using JavaScript
 
 

Downloads