Friday, March 1, 2013

Sending an email with JavaScript and ASP.NET


I recently ran into an issue where I wanted to have an HTML form send an email from a website.  I was building a website using entirely HTML, JavaScript, and CSS.  However, it is not possible to send an email from the client side; it must be handled on the server side.  In order to do this, your two best options are ASP.NET or PHP.  While searching for a solution I found that most people simply suggest building the entire thing in ASP.NET or PHP.  However, I was determined not to do this.  My goal was to write only what I needed in ASP.NET and leave the rest.  I chose to use C# because that was what I was the most experienced with.

After quite a bit of searching, I found the basis of what I needed to get started.  The jQuery JavaScript libraries have an Ajax function that can call an ASP.NET method on the server.  The jQuery.ajax() function has many possible uses but we will just use it to call an ASP.NET function to send an email here.

Let’s start by building our HTML form for the user to fill out and submit.  In this example we have a name, email, and message input along with a submit button.  We leave the action blank and use a class called “validate-form” to type it to the CSS.  We will not discuss validation here.

<form action="#" class="validate-form">
<fieldset>
<input type="text" id="Name" value="Name"/>
              <input type="text" id="Email" value="Email"/>
              <textarea cols="10" rows="5" 
                        id="Comments">Comments</textarea>
              <input type="submit" id="Submit-footer" 
                     value="Send the Message"/>
</fieldset>
</form>

Now let’s create the ASP.NET portion of the project.  Create a new ASPX file and name it “SendEmail.aspx”.  First add a reference to the System.Net.Mail libraries at the top:

using System.Net.Mail;

Now create a new procedure called “SendMessage”.  The new procedure will take parameters for the name, email, and message.  The code below is a pretty basic method of sending an email so I will not go into detail.  Key points are the server name and the email address to send the email to.

[System.Web.Services.WebMethod]
public static void SendMessage(string name, string fromEmail, string comments)
{
const string SERVER = "relay-hosting.secureserver.net";
       const string TOEMAIL = "info@sample.com";
       MailAddress from = new MailAddress(fromEmail);
       MailAddress to = new MailAddress(TOEMAIL);
       MailMessage message = new MailMessage(from, to);

       message.Subject = "Web Site Contact Inquiry from " + name;
       message.Body = "Message from: " + name + " at "
                      fromEmail + "\n\n" + comments;
       message.IsBodyHtml = false;
       SmtpClient client = new SmtpClient(SERVER);
       client.Send(message);
 }

Next create a JavaScript file called “functions.js”.  We will create a function that will kick off when the user clicks the submit button.  There are several ways to do this, so feel free to use whichever works best for you.  First we get the three inputs from the user.  Next we call the jQuery.ajax() function.  The url parameter is the path to the .aspx file and it’s method.  The data parameter is used to feed the input to the ASP.NET method we just created.  The format is {‘parameter1’: ‘userinput’, …}, where “parameter1” is the name of the parameter in the ASP.NET procedure.  In this example, we built the data string first.  The other parameters for the jQuery.ajax() function along with more parameters can be found in the documentation for the function.

$(function () {
    $('.validate-form').submit(function () {
       var name = document.getElementById("Name").value;
       var fromEmail = document.getElementById("Email").value;
       var comments = document.getElementById("Comments").value;
var data = "{'name': '" + name + "', 'fromEmail': '"
           fromEmail + "', 'comments': '" + comments + "'}";

        $.ajax({
            type: "POST",
            url: "SendEmail.aspx/SendMessage";
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json"
        });
    });
});

Finally we  need to add some items to the header of the HTML document.  We need to add a reference to the stylesheet, which we will not discuss here.  Next we need to add reference to two JavaScript files.  First download the jQuery file from here.

<link rel="stylesheet" href="css/style.css" type="text/css" 
      media="all" />
<script src="js/jquery-1.4.2.js" type="text/javascript" 
        charset="utf-8"></script>
<script src="js/functions.js" type="text/javascript" 
        charset="utf-8"></script>

That’s it.  Now when the user clicks the submit button, and email will be generated on the server and sent to the specified email address.  As with all code, there are many ways to do different parts of this example.  Use whichever works best for you.

14 comments:

  1. This is awesome, thanks for the great class. I wonder if this works with JavaScript as well.
    PHP developers | ASP.NET developers

    ReplyDelete
  2. Hi,

    Thank you for your post. I am trying to put your code on my site.Master because I want people can send me their contact wherever they want. And I just want to receive their name and email address. The issue is I receive the error: "The HTTP verb POST used to access path '/' is not allowed.". Please kindly help me out. Thank you

    ReplyDelete
    Replies
    1. Have a look at the following post. Most likely the "action" parameter is the source of your troubles.

      http://stackoverflow.com/questions/4610433/the-http-verb-post-used-to-access-path-my-path-is-not-allowed

      Delete
  3. Yes make sure you use action="#" in your form. Hope this helps.

    ReplyDelete
    Replies
    1. Also make sure you don't have method="post" in the HTML for the form.

      Delete
  4. Thank you for this post :)
    I'm starting my adventure with JavaScript and ASP.NET, and this post helped me a lot :)

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. Great Article ,
    But i am getting following error, please give me solution
    Mailbox name not allowed. The server response was: sorry, relaying denied from your location [14.194.75.202] (#5.7.1)

    ReplyDelete
  7. i wants to complete code of comment

    ReplyDelete
  8. i want functions.js jquery please post it

    ReplyDelete
  9. please send complete source code..

    ReplyDelete
  10. how to a add a port to the SMTP server ?

    ReplyDelete
  11. Thanks... The code is working in all environment.

    ReplyDelete
  12. I am very enjoyed for this blog. Its an informative topic. It help me very much to solve some problems. Its opportunity are so fantastic and working style so speedy.
    defer parsing of js wordpress

    ReplyDelete