In this article I will explain with an example, how to send email using
JavaScript in ASP.Net with C# and VB.Net.
The Email will be sent by calling a
Web Method using
AJAX and
XmlHttpRequest (XHR) in ASP.Net.
HTML Markup
The following HTML Markup consists of:
TextBox – For capturing the values of Recipient
Email address, Subject, Body.
Button – For sending email.
The Button has been assigned with an
OnClientClick event handler which makes call to a
JavaScript function.
<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" OnClientClick="return SendEmail()" /></td>
</tr>
</table>
Mail Server Settings in Web.Config file
The following Mail Server settings need to be saved 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
Server Side Web Methods for sending Email
The following
Web Method SendEmail accepts email address (toEmail), Subject and Body parameters and returns the String message.
Note: The method is declared as static (C#) and Shared (VB.Net) and also it is declared as WebMethod unless you do this you won’t be able to call the methods.
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 which will be later displayed using
JavaScript Alert Message Box.
C#
[WebMethod]
public static 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;
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 = smtpSection.Network.DefaultCredentials;
smtp.Credentials = networkCred;
smtp.Port = smtpSection.Network.Port;
smtp.Send(mm);
}
}
return "Email sent.";
}
VB.Net
<WebMethod()>
Public Shared 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
Using 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
End Using
Return "Email sent."
End Function
JavaScript XmlHttpRequest (XHR) function to send email in ASP.Net
The
SendEmail JavaScript function is called when the
Send Button is clicked.
Inside this function the
ToEmail,
Subject and
Body values are fetched from the TextBoxes and an
AJAX call is made using
JavaScript XmlHttpRequest (XHR) function to the server and are passed as parameters to the
Web Method SendEmail.
The value returned from the Web Method is fetched inside the
onreadystatechange event handler of the
JavaScript XmlHttpRequest (XHR) function and displayed using
JavaScript Alert Message Box.
<script type="text/javascript">
function SendEmail() {
var toEmail = document.getElementById("<%= txtTo.ClientID%>").value;
var subject = document.getElementById("<%= txtSubject.ClientID%>").value;
var body = document.getElementById("<%= txtBody.ClientID%>").value;
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 = "CS.aspx/SendEmail";
request.open("POST", url, false);
var params = "{toEmail: '" + toEmail + "', subject: '" + subject + "', body: '" + body + "' }";
request.setRequestHeader("Content-Type","application/json");
request.onreadystatechange = function () {
if (request.readyState == 4 &&request.status == 200) {
alert(JSON.parse(request.responseText).d);
}
};
request.send(params);
}
return false;
};
</script>
Errors while sending Email using Gmail
The following error occurs when you try to send email using
Gmail credentials in your
ASP.Net 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
Received Email
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Downloads