angle

Sending email with jQuery and a web service.

This article will show you how to send an email with jQuery and an ASP.NET web service (asmx). Using the jQuery ajax method, we will sumbit the contact form information in JSON to the asmx service. Also this article is written with WebForm in mind and not MVC.

The first step will be to set up the asmx web service. In the Solution Explorer, right click on the project and click Add>New Item>Web Service. Name the service MailService.asmx and click Add. Open the the codbehind and you'll add a SendEmail method with the following code. Also don't forget to import the System.Net.Mail

    <WebMethod()> _
    Public Sub SendMail(ByVal email As String, ByVal fname As String, ByVal lname As String, ByVal inquiry As String)
        'create the mail message
        Dim mail As New MailMessage()
        'set the addresses
        mail.From = New MailAddress(email)
        mail.To.Add("siteadmin@xyz.com")
        'set the content
        mail.Subject = "Contact Email"
        mail.IsBodyHtml = True
        mail.Body = "This is the body of the email"
        'send the message
        Dim smtp As New SmtpClient()
        smtp.Send(mail)
    End Sub

You'll also need to uncomment the following line towards the top of the asmx file. This enables the service to be called from script, not just ASP.NET AJAX but also jQuery. .

<System.Web.Script.Services.ScriptService()> 

After you have added the code to the asmx service file, you'll need to a Service Reference. Right click on the project in the Solution Explorer or right click on the Service References folder and select Add Service Reference. In the dialog window specify the address of the service and click Go. You can give the service a different namespace than ServiceReference1 - I used MailServiceProxy. Click OK. You'll notice that there are new entries in Web.config. Don't forget to upload the newly altered web.config, asmx file and the recomplied dll when it is time to put it all live.

You'll a new web form to contain the contact form and jQuery code. You can see what my final form looks like here. Here is my code:

<div id="divContactForm">
<fieldset>
<legend>Contact me with ASP.NET and jQuery</legend>
<label>First Name: </label><asp:Textbox ID="txtFName" runat="server" CssClass="txtboxes" /><br />
<label>Last Name: </label><asp:Textbox ID="txtLName" runat="server" CssClass="txtboxes" /><br />
<label>Email:  </label><asp:Textbox ID="txtEmail" runat="server" CssClass="txtboxes" /><br />
<label>Inquiry: </label><asp:Textbox ID="txtInquiry" runat="server" CssClass="txtarea" TextMode="MultiLine"  /><br />

<a href="javascript:;" id="aSubmitForm">Send Email with jQuery</a>

</fieldset>
</div>


<div id="divEmailSent"></div>

In my code I have 2 divs - one holds the form and one will hold the message  that will be displayed to the user when the email is sent. I also have a simple hyperlink to which the ajax event will be bound.

Now for the jQuery code. The concept is very similiar to the technique presented in the previous article "Check Username Availability with JQuery". As in the previous article we will use the $.ajax method to submit the contact form data to the web service.

<script type="text/javascript">
    var $j = jQuery.noConflict(); //set no conflict so you can use with MS AJAX.
    $j(document).ready(function() {
        $j("#divContactForm").show();
        $j("#divEmailSent").hide();
        // Add the service method call as an onclick handler for the a tag
        $j("#aSubmitForm").click(function() {
            $j.ajax({
                type: "POST",
                url: "http://localhost:36742/services/mailservice.asmx",
                data: "{'email':'" + $j("#<%=txtEmail.ClientID %>").val() + "',  
                'fname':'" + $j("#<%=txtFName.ClientID %>").val() + "',
                'lname':'" + $j("#<%=txtLName.ClientID %>").val() + "',
                'inquiry':'" + $j("#<%=txtInquiry.ClientID %>").val() + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(message) {
                  //Hide the contact form and show the message letting the user know the email has been sent
                    $j("#divContactForm").hide();
                    $j("#divEmailSent").show();
                    $j("#divEmailSent").text("Your email has been sent via jQuery and a web service.");
                },
                error: function(errormessage) {
                //you would not show the real error to the user - this is just to see if everything is working
                    
                    $j("#divEmailSent").show();
                    $j("#divEmailSent").text(errormessage.responseText);
                   
                }
            });
        });

    });
 </script>

In the above I call jQuery.noConflict because I use both MS AJAX and jQuery on this site. Calling noConflict allows them to play nicely. As soon as the DOM is ready, I show the div that holds the contact form andhide the div that holds the message displayed to the user once the form is submitted. jQuery's $j.ajax method is triggered when the hyperlink is clicked. The value of the url parameter is the address of the mail service. You must specify the method as part of the url as well. The values from the contact form will be submitted as JSON data. A little server side logic is injecte dinto the jQuery to get the client side IDs of the textbox controls. The val() method in jQuery allows us to obtain the text of each textbox control. If everything goes well, the contact form div is hidden while the divEmailSent is shown with a message indicating to the user that the email has been sent. The demo is fully functional - I will actually get any email sent via the contact form.

In this example, I did not institute an error handling logic on the server side. Also the contact form has no client side validation.

The email service can be consumed not just by a web page but also by a silverlight application for example. Utilizing jQuery to submit the form, we eliminated the postback - if a user reloads the page the form is not submitted a second time. This same techique can aplied toother situations such as a login form - your only limitations is your imagination.

Rate This Article (5 being the best)

Comments: Email:
(optional)
Rate It


Kick this article on dotnetkicks.com