{"id":911,"date":"2018-08-18T11:50:24","date_gmt":"2018-08-18T11:50:24","guid":{"rendered":"http:\/\/www.netexl.com\/blog\/?p=911"},"modified":"2026-04-02T09:51:28","modified_gmt":"2026-04-02T09:51:28","slug":"send-email-from-godaddy-asp-net-application-using-google-smtp","status":"publish","type":"post","link":"https:\/\/www.netexl.com\/blog\/send-email-from-godaddy-asp-net-application-using-google-smtp\/","title":{"rendered":"Send Email from Asp.Net Application using Google Account and SMTP"},"content":{"rendered":"<p>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 &#8220;Contact Us&#8221;. 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.<\/p>\n<p>Create a web service as following<\/p>\n<pre class=\"lang:default decode:true\">using System;\r\nusing System.Configuration;\r\nusing System.Net.Mail;\r\nusing System.Web.Services;\r\n\r\nnamespace GoDaddy.Email\r\n{\r\n    \/\/\/ &lt;summary&gt;\r\n    \/\/\/ Summary description for Mail\r\n    \/\/\/ &lt;\/summary&gt;\r\n    [WebService(Namespace = \"http:\/\/tempuri.org\/\")]\r\n    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]\r\n    [System.ComponentModel.ToolboxItem(false)]\r\n    \/\/ To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. \r\n    [System.Web.Script.Services.ScriptService]\r\n    public class Mail : System.Web.Services.WebService\r\n    {\r\n        [WebMethod]\r\n        public string SendEmail(string to, string subject, string body)\r\n        {\r\n            try\r\n            {\r\n                var fromEmailAddress = ConfigurationManager.AppSettings[\"FromEmailAddress\"].ToString();\r\n                var fromEmailDisplayName = ConfigurationManager.AppSettings[\"FromEmailDisplayName\"].ToString();\r\n                var fromEmailPassword = ConfigurationManager.AppSettings[\"FromEmailPassword\"].ToString();\r\n                var smtpHost = ConfigurationManager.AppSettings[\"SMTPHost\"].ToString();\r\n                var smtpPort = ConfigurationManager.AppSettings[\"SMTPPort\"].ToString();\r\n\r\n                MailMessage mailMessage = new MailMessage();\r\n                mailMessage.To.Add(to);\r\n                mailMessage.From = new MailAddress(fromEmailAddress, fromEmailDisplayName);\r\n                mailMessage.Subject = subject;\r\n                mailMessage.Body = body;\r\n                SmtpClient smtpClient = new SmtpClient(smtpHost, Convert.ToInt32(smtpPort));\r\n                smtpClient.EnableSsl = true;\r\n                smtpClient.Credentials = new System.Net.NetworkCredential(fromEmailAddress, fromEmailPassword);\r\n\r\n                smtpClient.Send(mailMessage);\r\n                return \"Success\";\r\n            }\r\n            catch (Exception ex)\r\n            {\r\n                return ex.Message;\r\n            }\r\n        }\r\n    }\r\n}\r\n<\/pre>\n<p>In order for the method to be called using AJAX make sure to uncomment [System.Web.Script.Services.ScriptService] in the web service code.<\/p>\n<p>Add following appsettings in web.config<\/p>\n<pre class=\"lang:default decode:true\">  &lt;appSettings&gt;\r\n    &lt;add key=\"FromEmailAddress\" value=\"info@yourdomain.com\"\/&gt;\r\n    &lt;add key=\"FromEmailDisplayName\" value=\"Support\"\/&gt;\r\n    &lt;add key=\"FromEmailPassword\" value=\"password\"\/&gt;\r\n    &lt;add key=\"SMTPHost\" value=\"smtp.gmail.com\"\/&gt;\r\n    &lt;add key=\"SMTPPort\" value=\"587\"\/&gt;\r\n  &lt;\/appSettings&gt;<\/pre>\n<p>Change values and replace email and password to your account credentials. Leave SMTPhost and port as-is.<\/p>\n<p>We will now create a simple HTML page to input the data<\/p>\n<pre class=\"lang:default decode:true\">&lt;!DOCTYPE html&gt;\r\n&lt;html&gt;\r\n&lt;head&gt;\r\n    &lt;title&gt;Send Email&lt;\/title&gt;\r\n\t&lt;meta charset=\"utf-8\" \/&gt;\r\n    &lt;link rel=\"stylesheet\" href=\"css\/style.css\" \/&gt;\r\n    &lt;script src=\"js\/jquery.min.js\"&gt;&lt;\/script&gt;\r\n&lt;\/head&gt;\r\n&lt;body&gt;\r\n    &lt;div id=\"contact-area\"&gt;\r\n        &lt;div&gt;\r\n            &lt;label&gt;Email:&lt;\/label&gt;\r\n            &lt;input id=\"email\" type=\"email\" maxlength=\"50\" \/&gt;\r\n        &lt;\/div&gt;\r\n        &lt;div&gt;\r\n            &lt;label&gt;Subject:&lt;\/label&gt;\r\n            &lt;input id=\"subject\" type=\"text\" maxlength=\"50\" \/&gt;\r\n        &lt;\/div&gt;\r\n        &lt;div&gt;\r\n            &lt;label&gt;Message:&lt;\/label&gt;\r\n            &lt;textarea id=\"message\" type=\"text\" rows=\"5\" cols=\"50\" maxlength=\"1000\"&gt;&lt;\/textarea&gt;\r\n        &lt;\/div&gt;\r\n        &lt;div&gt;\r\n            &lt;input id=\"btnSend\" type=\"button\" name=\"Send\" value=\"Send\" class=\"submit-button\"\/&gt;\r\n        &lt;\/div&gt;\r\n        &lt;div id=\"error\" class=\"error\"&gt;&lt;\/div&gt;\r\n        &lt;div id=\"success\" class=\"success\"&gt;&lt;\/div&gt;\r\n    &lt;\/div&gt;\r\n&lt;\/body&gt;\r\n&lt;\/html&gt;\r\n<\/pre>\n<p>Now the last piece is to simply call the web service\u00a0by passing required data for the email<\/p>\n<pre class=\"lang:default decode:true\">    &lt;script type=\"text\/javascript\"&gt;\r\n        function isValidEmail(email) {\r\n            var pattern = \/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\\.([a-zA-Z])+([a-zA-Z])+\/;\r\n            return pattern.test(email);\r\n        }\r\n\r\n        function validate() {\r\n            var isValid = false;\r\n            var email = $('#email').val();\r\n            if (isValidEmail(email)) {\r\n                var subject = $('#subject').val();\r\n                var message = $('#message').val();\r\n                if (subject === '' || message === '') {\r\n                    $('#error').html(\"Subject or Message cannot be blank\");\r\n                } else {\r\n                    isValid = true;\r\n                }\r\n            } else {\r\n                $('#error').html(\"Invalid Email\");\r\n            }\r\n            return isValid;\r\n        }\r\n\r\n        function sendMail() {\r\n            $('#btnSend').prop('disabled', true);\r\n            $('#success').html(\"\");\r\n            $('#error').html(\"\");\r\n            if (validate()) {\r\n                var to = $('#email').val();\r\n                var subject = $('#subject').val();\r\n                var body = $('#message').val();\r\n\r\n                var param = \"{'to':\" + JSON.stringify(to) + \", 'subject':\" + JSON.stringify(subject) + \", 'body':\" + JSON.stringify(body) + \"}\"; \/\/JSON.stringify(mail);\r\n\r\n                $.ajax({\r\n                    type: \"POST\",\r\n                    url: \"\/Mail.asmx\/SendEmail\",\r\n                    contentType: \"application\/json; charset=utf-8\",\r\n                    data: param,\r\n                    dataType: \"json\",\r\n                    success: function (response) {\r\n                        var data = response.d;\r\n                        if (data != 'Success') {\r\n                            $('#error').html(\"Some error occurred..\");\r\n                        } else {\r\n                            $('#success').html(\"Mail sent\");\r\n                        }\r\n                        $('#btnSend').prop('disabled', false);\r\n                    },\r\n                    failure: function (response) {\r\n                        alert(response.d);\r\n                        $('#btnSend').prop('disabled', false);\r\n                    }\r\n                });\r\n            } else {\r\n                $('#btnSend').prop('disabled', false);\r\n            }\r\n        }\r\n\r\n        document.getElementById(\"btnSend\").addEventListener(\"click\", sendMail);\r\n    &lt;\/script&gt;<\/pre>\n<p>You can download complete code (along with solution package) <a href=\"https:\/\/github.com\/ngdevr\/AspNetMail\" target=\"_blank\">here<\/a>.<\/p>\n<p>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<\/p>\n<p><a href=\"https:\/\/myaccount.google.com\/security?pli=1#connectedapps\" target=\"_blank\">https:\/\/myaccount.google.com\/security?pli=1#connectedapps<\/a><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-916\" src=\"https:\/\/www.netexl.com\/blog\/wp-content\/uploads\/2018\/08\/lesssecureapps.png\" alt=\"\" width=\"625\" height=\"204\" srcset=\"https:\/\/www.netexl.com\/blog\/wp-content\/uploads\/2018\/08\/lesssecureapps.png 625w, https:\/\/www.netexl.com\/blog\/wp-content\/uploads\/2018\/08\/lesssecureapps-300x98.png 300w, https:\/\/www.netexl.com\/blog\/wp-content\/uploads\/2018\/08\/lesssecureapps-280x91.png 280w\" sizes=\"auto, (max-width: 625px) 100vw, 625px\" \/><\/p>\n","protected":false},"excerpt":{"rendered":"<p>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 &#8220;Contact Us&#8221;. 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 { \/\/\/ &lt;summary&gt; \/\/\/ Summary description for Mail \/\/\/ &lt;\/summary&gt; [WebService(Namespace = &#8220;http:\/\/tempuri.org\/&#8221;)] [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)[&#8230;]<\/p>\n","protected":false},"author":5,"featured_media":1539,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[16,14,24,17,22],"tags":[],"class_list":["post-911","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-asp-net","category-how-to","category-javascript","category-jquery","category-quick-tip"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.netexl.com\/blog\/wp-json\/wp\/v2\/posts\/911","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.netexl.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.netexl.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.netexl.com\/blog\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/www.netexl.com\/blog\/wp-json\/wp\/v2\/comments?post=911"}],"version-history":[{"count":4,"href":"https:\/\/www.netexl.com\/blog\/wp-json\/wp\/v2\/posts\/911\/revisions"}],"predecessor-version":[{"id":919,"href":"https:\/\/www.netexl.com\/blog\/wp-json\/wp\/v2\/posts\/911\/revisions\/919"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.netexl.com\/blog\/wp-json\/wp\/v2\/media\/1539"}],"wp:attachment":[{"href":"https:\/\/www.netexl.com\/blog\/wp-json\/wp\/v2\/media?parent=911"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.netexl.com\/blog\/wp-json\/wp\/v2\/categories?post=911"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.netexl.com\/blog\/wp-json\/wp\/v2\/tags?post=911"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}