In this article I will explain with an example, how to send email using jQuery in ASP.Net using C# and VB.Net.
The jQuery AJAX function will call a Web Service (Web Method) which will send email using Gmail SMTP Mail Server.
Once the Email is sent, a Confirmation will be sent back to the jQuery AJAX function which in turn will be display a Success message using JavaScript Alert Message Box.
HTML Markup
The HTML Markup has a form with some fields such as Recipient Email address, Subject, Body and a Button to send the email.
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>To:</td>
<td><asp:TextBox ID="txtTo" runat="server" /></td>
</tr>
<tr>
<td>Subject:</td>
<td><asp:TextBox ID="txtSubject" runat="server" /></td>
</tr>
<tr>
<td valign = "top">Body:</td>
<td><asp:TextBox ID="txtBody" runat="server" TextMode="MultiLine" Height="150" Width="200" /></td>
</tr>
<tr>
<td></td>
<td><asp:Button ID="btnSend" Text="Send" runat="server" /></td>
</tr>
</table>
Mail Server Settings in Web.Config file
Following are the Mail Server settings in the Web.Config file.
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="sender@gmail.com">
<network
host="smtp.gmail.com"
port="587"
enableSsl="true"
userName="sender@gmail.com"
password="SenderGmailPassword"
defaultCredentials="true"/>
</smtp>
</mailSettings>
</system.net>
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)
Namespaces
You will need to import the following namespaces.
C#
using System.Net;
using System.Net.Mail;
using System.Web.Services;
using System.Configuration;
using System.Net.Configuration;
VB.Net
Imports System.Net
Imports System.Net.Mail
Imports System.Web.Services
Imports System.Configuration
Imports System.Net.Configuration
Adding Web Service
You will need to add a new Web Service (ASMX) file using Add New Item Dialog of Visual Studio as shown below.
Configuring Web Service to handle jQuery AJAX calls
By default the Web Service will not accept requests from client side sent using jQuery AJAX. In order to allow a Web Service handle jQuery AJAX calls, the ScriptService attribute needs to be specified to the Web Service class.
Sending Email using Web Service in ASP.Net
The following Web Service consists of a Web Method SendEmail, which accepts email address (toEmail), Subject and Body parameters and returns the String message.
The Sender email address (from) is fetched from the SmtpSection of the Web.Config file.
All these values are set into an object of the MailMessage class.
Finally, object of the SmtpClient class is created and the settings of the Mail Server such has Host, Port, DefaultCredentials, EnableSsl, Username and Password are fetched from the mailSettings section of the Web.Config file and attached to the SmtpClient class object.
Finally, a String message is returned.
C#
///<summary>
/// Summary description for Service
///</summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class Service : System.Web.Services.WebService
{
public Service()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string SendEmail(string toEmail, string subject, string body)
{
SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
using (MailMessage mm = new MailMessage(smtpSection.From, toEmail))
{
mm.Subject = subject;
mm.Body = body;
mm.IsBodyHtml = false;
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 = smtpSection.Network.DefaultCredentials;
smtp.Credentials = networkCred;
smtp.Port = smtpSection.Network.Port;
smtp.Send(mm);
}
return "Email sent.";
}
}
VB.Net
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class Service
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function SendEmail(ByVal toEmail As String, ByVal subject As String, ByVal body As String) As String
Dim smtpSection As SmtpSection = CType(ConfigurationManager.GetSection("system.net/mailSettings/smtp"), SmtpSection)
Using mm As MailMessage = New MailMessage(smtpSection.From, toEmail)
mm.Subject = subject
mm.Body = body
mm.IsBodyHtml = False
Dim smtp As SmtpClient = New SmtpClient
smtp.Host = smtpSection.Network.Host
smtp.EnableSsl = smtpSection.Network.EnableSsl
Dim networkCred As NetworkCredential = New NetworkCredential(smtpSection.Network.UserName, smtpSection.Network.Password)
smtp.UseDefaultCredentials = smtpSection.Network.DefaultCredentials
smtp.Credentials = networkCred
smtp.Port = smtpSection.Network.Port
smtp.Send(mm)
End Using
Return "Email sent."
End Function
End Class
jQuery AJAX function to send emails using Web Service in ASP.Net
When the Send Button is clicked, a jQuery AJAX call to the Web Service is made and the ToEmail, Subject and Body values are fetched from the TextBoxes and are passed as parameters to the Web Method SendEmail.
The value returned from the Web Service’s Web Method is fetched inside the Success event handler of the jQuery AJAX function and displayed using JavaScript Alert Message Box.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("[id*=btnSend]").click(function () {
var toEmail = $.trim($("[id*=txtTo]").val());
var subject = $.trim($("[id*=txtSubject]").val());
var body = $.trim($("[id*=txtBody]").val());
$.ajax({
type: "POST",
url: "Service.asmx/SendEmail",
data: "{ toEmail: '" + toEmail + "', subject: '" + subject + "', body: '" + body + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert(r.d);
},
error: function (r) {
alert(r.responseText);
},
failure: function (r) {
alert(r.responseText);
}
});
return false;
});
});
</script>
Errors while sending Email using Gmail
Screenshots
Email Form
Received Email
Downloads