In this article I will explain with an example, how to send Email using Web API and jQuery AJAX in ASP.Net Core.
When the Send Button is clicked, the SendEmail Action method of the Web API is called using jQuery AJAX and the Email is sent.
Note: For beginners in ASP.Net Core and Web API, please refer my article: .Net Core 8: Create Web API in Visual Studio 2022 step by step for details about using and configuring Web API.
 
 

Mail Server Settings in AppSettings.json file

The following Mail Server settings need to be saved in the AppSettings.json 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.
 
{
  "Smtp": {
    "Server": "smtp.gmail.com",
    "Port": 587,
    "EnableSsl": true,
    "DefaultCredentials": true,
    "From": "sender@gmail.com",
    "Username": "sender@gmail.com",
    "Password": "GMAILor2STEP-PASSWORD"
  }
}
 
 

Sending Email using Gmail SMTP

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 Smtp 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 To { get; set; }
    public string Subject { get; set; }
    public string Body { get; set; }
}
 
 

Controller

The Controller consists of the 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 IActionResult Index()
    {
        return View();
    }
}
 
 

Namespaces

You will need to import the following namespaces.
using System.Net;
using System.Net.Mail;
using WebAPI_Core_8.Models;
using Microsoft.AspNetCore.Mvc;
 
 

Web API Controller

The Web API Controller consists of following Action methods.

Action method for Sending Email

This Action method handles the POST call made using jQuery AJAX function.
Inside this Action method, the Sender email address (from) is fetched from the SmtpSection of the AppSettings.json 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 FALSE.
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 AppSettings.json 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 : ControllerBase
{
    public IConfiguration Configuration { get; set; }
    public AjaxAPIController(IConfiguration configuration)
    {
        this.Configuration = configuration;
    }
 
    [Route("AjaxMethod")]
    [HttpPost]
    [ValidateAntiForgeryToken]
    public string AjaxMethod(EmailModel model)
    {
        //Read SMTP section from AppSetting.json.
        string host = this.Configuration.GetValue<string>("Smtp:Server");
        int port = this.Configuration.GetValue<int>("Smtp:Port");
        bool enableSsl = this.Configuration.GetValue<bool>("Smtp:EnableSsl");
        bool defaultCredentials = this.Configuration.GetValue<bool>("Smtp:DefaultCredentials");
        string from = this.Configuration.GetValue<string>("Smtp:From");
        string userName = this.Configuration.GetValue<string>("Smtp:Username");
        string password = this.Configuration.GetValue<string>("Smtp:Password");
 
        using (MailMessage mm = new MailMessage(from, model.To))
        {
            mm.Subject = model.Subject;
            mm.Body = model.Body;
            mm.IsBodyHtml = false;
            using (SmtpClient smtp = new SmtpClient())
            {
                smtp.Host = host;
                smtp.EnableSsl = enableSsl;
                NetworkCredential networkCred = new NetworkCredential(userName, password);
                smtp.UseDefaultCredentials = defaultCredentials;
                smtp.Credentials = networkCred;
                smtp.Port = port;
                smtp.Send(mm);
            }
        }
 
        return "Email sent successfully.";
    }
}
 
 

View

HTML Markup

The View consists of two TextBoxes, a TextArea and a Button.
The Button has been assigned with a jQuery 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 jQuery AJAX function.
Note: For more information on how to call Web API using jQuery AJAX, please refer the article: Call ASP.Net Core Web API using jQuery 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>
    @Html.AntiForgeryToken()
    <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" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#btnSend").click(function () {
                var email = {};
                email.To = $("#txtEmail").val() ;
                email.Subject = $("#txtSubject").val();
                email.Body = $("#txtBody").val();
                $.ajax({
                    type: "POST",
                    url: "/api/AjaxAPI/AjaxMethod",
                    beforeSend:function (xhr) {
                        xhr.setRequestHeader("XSRF-TOKEN",
                            $('input:hidden[name="__RequestVerificationToken"]').val());
                    },
                    data: JSON.stringify(email),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        alert(response);
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    },
                    error: function (response) {
                        alert(response.responseText);
                    }
                });
            });
        });
    </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

 
 

Screenshot

Email Form

ASP.Net Core: Send Email using Web API
 

Received Email

ASP.Net Core: Send Email using Web API
 
 

Downloads