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 Asp.net 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 = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 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 Mail : System.Web.Services.WebService
    {
        [WebMethod]
        public string SendEmail(string to, string subject, string body)
        {
            try
            {
                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.To.Add(to);
                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);

                smtpClient.Send(mailMessage);
                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

  <appSettings>
    <add key="FromEmailAddress" value="info@yourdomain.com"/>
    <add key="FromEmailDisplayName" value="Support"/>
    <add key="FromEmailPassword" value="password"/>
    <add key="SMTPHost" value="smtp.gmail.com"/>
    <add key="SMTPPort" value="587"/>
  </appSettings>

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>
<html>
<head>
    <title>Send Email</title>
	<meta charset="utf-8" />
    <link rel="stylesheet" href="css/style.css" />
    <script src="js/jquery.min.js"></script>
</head>
<body>
    <div id="contact-area">
        <div>
            <label>Email:</label>
            <input id="email" type="email" maxlength="50" />
        </div>
        <div>
            <label>Subject:</label>
            <input id="subject" type="text" maxlength="50" />
        </div>
        <div>
            <label>Message:</label>
            <textarea id="message" type="text" rows="5" cols="50" maxlength="1000"></textarea>
        </div>
        <div>
            <input id="btnSend" type="button" name="Send" value="Send" class="submit-button"/>
        </div>
        <div id="error" class="error"></div>
        <div id="success" class="success"></div>
    </div>
</body>
</html>

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);
            $('#success').html("");
            $('#error').html("");
            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);

                $.ajax({
                    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) {
                        alert(response.d);
                        $('#btnSend').prop('disabled', false);
                    }
                });
            } else {
                $('#btnSend').prop('disabled', false);
            }
        }

        document.getElementById("btnSend").addEventListener("click", sendMail);
    </script>

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

https://myaccount.google.com/security?pli=1#connectedapps


Leave A Comment

Your email address will not be published.