How To Build a JSON Web Service to Send Mail in ASP.Net

by Max Slabyak

I was pleasantly surprised to see the traffic analytics on a post I wrote a while ago on Using jQuery to Send Email with Web Services. However, I found some who were still requiring assistance writing the actual .NET web service. Here you go.

In Visual Studio, when you create a web service (ASMX), the default format is SOAP. You will need add a couple of attributes to the code to make it return results in a true JSON format.

  1. First requirement is that you do a POST, but the AJAX call already takes care of that.
  2. Your class is going to need the
    [ScriptService]

    attribute so that you can call the web service from javascript.

  3. Your method responsible for sending mail will need this attribute:
    [ScriptMethod(UseHttpGet = false,ResponseFormat = ResponseFormat.Json)]


Everything else is pretty self-explanatory with the comments provided in the code. If the try/catch code block jumps out at you as being way over-simplified, it’s because the AJAX listens for a successful HTTP 200 result. If there is an error, caught with the generic Exception class, you can use jQuery and your code to notify the user that mail wasn’t sent successfully.

Also, if this web service is hosted separately from your mail server, you can just uncomment the SmtpClient properties to specify extra properties, including port, SSL, and credentials. If you can’t find a mail server to use, you can actually use gmail as a server. Just use SSL, Port 587, smtp.gmail.com, and your email/password for credentials and you are done. Just remember to log in once in a while, otherwise Google will think you are a bot.

Without further ado, the code:


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

namespace MailService
{
    [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. 
    [ScriptService]
    public class Mail : WebService
    {

        [WebMethod]
        [ScriptMethod(UseHttpGet = false,ResponseFormat = ResponseFormat.Json)]
        public bool SendMail(string body,string to,string from,string subject)
        {

            var message = new MailMessage(from, to)
                {
                    Subject = subject
                    , Body = @body
                    , IsBodyHtml = true
                };
            var client = new SmtpClient("localhost") //or a different smtp server
            {
                // Credentials are necessary if the server requires the client  
                // to authenticate before it will send e-mail on the client's behalf.
                UseDefaultCredentials = true

                //to use a username/pass with your SMTP server, 
                //set UseDefaultCredentials to false and use the line below
                //smtp.Credentials = new NetworkCredential("username",  "password");

                //to use a non-standard port, uncomment the line below.
                //,Port = 587 

                //to use SSL, uncomment the line below
                //,EnableSsl = true

            }; 

            try
            {
                client.Send(message);
                return true;
            }
            catch (Exception)
            {
                return false;

            }       
        }
    }
}

Share

2 thoughts on “How To Build a JSON Web Service to Send Mail in ASP.Net

Leave a Reply

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