Send Email from Asp.Net Application using Google Account and SMTP

In order to send mail from the application we can use SMTP server from Google (which off course has certain limitations). We can use a Google mail account and send the mail using SMTP server from Google. This works very well for applications which need to use a simple form such as “Contact Us”. An example of this is explained below. We will use AJAX to send the request to an ASP.Net web service which sends the mail from the server side.

Create a web service as following

using System;
using System.Configuration;
using System.Net.Mail;
using System.Web.Services;

namespace GoDaddy.Email
    /// <summary>
    /// Summary description for Mail
    /// </summary>
    [WebService(Namespace = "")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    public class Mail : System.Web.Services.WebService
        public string SendEmail(string to, string subject, string body)
                var fromEmailAddress = ConfigurationManager.AppSettings["FromEmailAddress"].ToString();
                var fromEmailDisplayName = ConfigurationManager.AppSettings["FromEmailDisplayName"].ToString();
                var fromEmailPassword = ConfigurationManager.AppSettings["FromEmailPassword"].ToString();
                var smtpHost = ConfigurationManager.AppSettings["SMTPHost"].ToString();
                var smtpPort = ConfigurationManager.AppSettings["SMTPPort"].ToString();

                MailMessage mailMessage = new MailMessage();
                mailMessage.From = new MailAddress(fromEmailAddress, fromEmailDisplayName);
                mailMessage.Subject = subject;
                mailMessage.Body = body;
                SmtpClient smtpClient = new SmtpClient(smtpHost, Convert.ToInt32(smtpPort));
                smtpClient.EnableSsl = true;
                smtpClient.Credentials = new System.Net.NetworkCredential(fromEmailAddress, fromEmailPassword);

                return "Success";
            catch (Exception ex)
                return ex.Message;

In order for the method to be called using AJAX make sure to uncomment [System.Web.Script.Services.ScriptService] in the web service code.

Add following appsettings in web.config

    <add key="FromEmailAddress" value=""/>
    <add key="FromEmailDisplayName" value="Support"/>
    <add key="FromEmailPassword" value="password"/>
    <add key="SMTPHost" value=""/>
    <add key="SMTPPort" value="587"/>

Change values and replace email and password to your account credentials. Leave SMTPhost and port as-is.

We will now create a simple HTML page to input the data

<!DOCTYPE html>
    <title>Send Email</title>
	<meta charset="utf-8" />
    <link rel="stylesheet" href="css/style.css" />
    <script src="js/jquery.min.js"></script>
    <div id="contact-area">
            <input id="email" type="email" maxlength="50" />
            <input id="subject" type="text" maxlength="50" />
            <textarea id="message" type="text" rows="5" cols="50" maxlength="1000"></textarea>
            <input id="btnSend" type="button" name="Send" value="Send" class="submit-button"/>
        <div id="error" class="error"></div>
        <div id="success" class="success"></div>

Now the last piece is to simply call the web service by passing required data for the email

    <script type="text/javascript">
        function isValidEmail(email) {
            var pattern = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
            return pattern.test(email);

        function validate() {
            var isValid = false;
            var email = $('#email').val();
            if (isValidEmail(email)) {
                var subject = $('#subject').val();
                var message = $('#message').val();
                if (subject === '' || message === '') {
                    $('#error').html("Subject or Message cannot be blank");
                } else {
                    isValid = true;
            } else {
                $('#error').html("Invalid Email");
            return isValid;

        function sendMail() {
            $('#btnSend').prop('disabled', true);
            if (validate()) {
                var to = $('#email').val();
                var subject = $('#subject').val();
                var body = $('#message').val();

                var param = "{'to':" + JSON.stringify(to) + ", 'subject':" + JSON.stringify(subject) + ", 'body':" + JSON.stringify(body) + "}"; //JSON.stringify(mail);

                    type: "POST",
                    url: "/Mail.asmx/SendEmail",
                    contentType: "application/json; charset=utf-8",
                    data: param,
                    dataType: "json",
                    success: function (response) {
                        var data = response.d;
                        if (data != 'Success') {
                            $('#error').html("Some error occurred..");
                        } else {
                            $('#success').html("Mail sent");
                        $('#btnSend').prop('disabled', false);
                    failure: function (response) {
                        $('#btnSend').prop('disabled', false);
            } else {
                $('#btnSend').prop('disabled', false);

        document.getElementById("btnSend").addEventListener("click", sendMail);

You can download complete code (along with solution package) here.

If you get an error, it might be possible that Google blocked it. You need to ensure that the setting to allow less secure apps is turned on

Leave A Comment

Your email address will not be published. Required fields are marked *