Send Email from GoDaddy Asp.Net Application

In my previous article we looked at how to use Google account and SMTP server to programatically send mail to an email address. We can use the same code with minor changes for GoDaddy application which is using shared hosting. We will develop a “Contact us” page here using SMTP server from GoDaddy.

The first step is to create a web service

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 email, string name, string body)
        {
            try
            {
                var toEmailAddress = ConfigurationManager.AppSettings["ToEmailAddress"].ToString();
                var smtpHost = ConfigurationManager.AppSettings["SMTPHost"].ToString();
                var smtpPort = ConfigurationManager.AppSettings["SMTPPort"].ToString();

                MailMessage mailMessage = new MailMessage();
                mailMessage.To.Add(toEmailAddress);
                mailMessage.From = new MailAddress(email, name);
                mailMessage.Subject = "Contact Us";
                mailMessage.Body = body;
                SmtpClient smtpClient = new SmtpClient(smtpHost, Convert.ToInt32(smtpPort));

                smtpClient.Send(mailMessage);
                return "Success";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
    }
}

The app settings are as following

  <appSettings>
    <add key="ToEmailAddress" value="contact@yourdomain.com"/>
    <add key="SMTPHost" value="relay-hosting.secureserver.net"/>
    <add key="SMTPPort" value="25"/>
  </appSettings>

The HTML page code for the contact us page is as following

<!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>Name:</label>
            <input id="name" 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 add the java script code as following in our HTML

    <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 name = $('#name').val();
                var message = $('#message').val();
                if (name === '' || message === '') {
                    $('#error').html("Name 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 email = $('#email').val();
                var name = $('#name').val();
                var body = $('#message').val();

                var param = "{'email':" + JSON.stringify(email) + ", 'name':" + JSON.stringify(name) + ", '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(data);
                        } 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>

The complete code can be downloaded from here.

Be aware that if you are setting email address entered by the user in the “from” address while sending the email, it may end up in SPAM folder of your mailbox. Alternatively you can use “from” and “to”addresses from your application domain itself and append user’s email address in the mail body.


Leave A Comment

Your email address will not be published.