Send Email Using jQuery and Web.API (Part 2)

As promised here is Part 2 of Sending Email using jquery and web.api (including some validation). If you missed Part 1 then get it here. It is important to realize that if you are going to use web.api for web forms then you need to add the following to the global.asax.
[code language=”vb”]
Imports System.Web.SessionState
Imports System.Web.Routing
Imports System.Web.Http

Public Class Global_asax
Inherits System.Web.HttpApplication

Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
RegisterRoutes(RouteTable.Routes)
End Sub

Sub RegisterRoutes(routes As routecollection)
routes.MapHttpRoute"ActionApi", "api/{controller}/{action}/{id}", New With {.id = System.Web.Http.RouteParameter.Optional})
routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", New With {.id = System.Web.Http.RouteParameter.Optional})
End Sub

End Class
[/code]
Then create a new web.api file and add the following;
[code language=”vb”]
Imports System.Net
Imports System.Web.Http
Imports System.Net.Http
Imports System.Collections.Generic
Imports System.ComponentModel.DataAnnotations
Imports System.Web
Imports System.Net.Mail
Imports System.IO

Public Class SendEmailController
Inherits ApiController

‘ POST api/
Public Function PostValue(ByVal EmailMessage As EmailClass) As HttpResponseMessage

If Not ModelState.IsValid Then
Dim errors = ModelState.Where(Function(s) s.Value.Errors.Count > 0).[Select](Function(s) New KeyValuePair(Of String, String)(s.Key, s.Value.Errors.First().ErrorMessage)).ToArray()
Dim responser = Request.CreateResponse(HttpStatusCode.BadRequest, errors)
Return responser
End If

Try
Dim mail As New MailMessage(EmailMessage.EmailFrom, EmailMessage.EmailTo)

Dim sendtoBCC As String = "test@arvixe.com"
If sendtoBCC <> "" Then
mail.Bcc.Add(sendtoBCC)
End If

mail.Subject = EmailMessage.Subject
mail.IsBodyHtml = True

mail.Body = GetEmailBody()

&amp;#039;// Replace placeholders in template.
mail.Body = mail.Body.Replace<%FromName%>, EmailMessage.Name)
mail.Body = mail.Body.Replace(<%FromCompany%>, EmailMessage.CompanyName)
mail.Body = mail.Body.Replace(<%FromAddress%>, EmailMessage.Address)
mail.Body = mail.Body.Replace(<%FromCity%>, EmailMessage.City)
mail.Body = mail.Body.Replace(<%FromStateZip%>, EmailMessage.State)
mail.Body = mail.Body.Replace(<%FromPhone%>, EmailMessage.PhoneNumber)
mail.Body = mail.Body.Replace(<%ToName%>, EmailMessage.EmailToName)
mail.Body = mail.Body.Replace(<%MessageBody%>, EmailMessage.Message)
mail.Body = mail.Body.Replace(<%Information%>, EmailMessage.Information)
mail.Body = mail.Body.Replace(<%Comment%>, EmailMessage.Comment)

&amp;#039;send the message
Dim smtp As New SmtpClient()
smtp.Send(mail)
Catch ex As Exception
If IsNothing(ex.InnerException) = True Then
Dim responser = Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message.ToString)
Return responser
Else
Dim responser = Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message.ToString)
Return responser
End If
End Try

EmailMessage.RtnID = 1

Dim response = Request.CreateResponse(HttpStatusCode.Created, EmailMessage)
response.Headers.Location = New Uri(Request.RequestUri, String.Format("customer/{0}", EmailMessage.RtnID))
Return response
End Function

Public Function GetEmailBody() As String
Dim templatePath As String = System.Web.HttpContext.Current.Server.MapPath("~/ContactForm.txt")
Dim sr As New StreamReader(templatePath)
Return sr.ReadToEnd()
End Function
End Class

Public Class EmailClass

<Required(ErrorMessage:="Name is required!")>
Public Property Name As String

<Required(ErrorMessage:="Email is Required!")> _
<RegularExpression("\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*([,;]\s*\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)*", ErrorMessage:="Invalid email address")> _
Public Property EmailFrom As String
Public Property CompanyName As String
Public Property Address As String
Public Property City As String
Public Property State As String
Public Property PhoneNumber As String
Public Property Subject As String
Public Property Message As String
Public Property Information As String
Public Property Comment As String
Public Property EmailTo As String
Public Property EmailToName As String
Public Property RtnID As Integer
End Class
[/code]
A few things to keep in mind and to take notice of in this web.api. First, I am using a class “container” to hold the email variables. I have also placed Required attributes to the Emailclass. When ModelState is validated then any requirements will trigger an error response back to the client. You can actually expand this to do a multitude of different validations as necessary. I am also using an email template and replace the variables with the content from the forms. The ContactForm.txt is here

. It is a just a text file.

Looking for quality web hosting? Look no further than Arvixe Web Hosting!

Tags: , , , , | Posted under ASP .NET 4.0, Programming/Coding | RSS 2.0

Author Spotlight

David Bauernschmidt

I live in the historical triangle of Virginia where I am married with two daughters. I have spent over 13 years working for a Fortune 500 company in the computer area. I started in VB 6.0 and by the time I ended my employment I was supervising a development team where we built many web applications. When my first daughter was born I wanted to spend more time with her so I left and became a programmer analyst for local government as well as launch my own company. Since then I have grown James River Webs into a profitable web design and application company helping small businesses create a big presence on the internet. As an employee I have created web application used by citizens and other companies. I enjoy fly fishing, and spending time with my family. I also enjoy learning new approaches and development tools when it comes to developing applications.

2 Comments on Send Email Using jQuery and Web.API (Part 2)

  1. Fred Mastro says:

    Here’s the c# version, not tested:

    public class SendEmailController : ApiController
    {

    public HttpResponseMessage PostValue(Email emailMessage) {
    if (!ModelState.IsValid) {
    var errors = ModelState.Where(s => s.Value.Errors.Count > 0).Select(s => new KeyValuePair(s.Key, s.Value.Errors.First().ErrorMessage)).ToArray();
    var responser = Request.CreateResponse(HttpStatusCode.BadRequest, errors);
    return responser;
    }
    try {
    var mail = new MailMessage(emailMessage.EmailFrom, emailMessage.EmailTo);

    const string sendtoBcc = “xxxx@gmail.com”;

    if (!string.IsNullOrEmpty(sendtoBcc)) {
    mail.Bcc.Add(sendtoBcc);
    }

    mail.Subject = emailMessage.Subject;
    mail.IsBodyHtml = true;

    mail.Body = GetEmailBody();

    if (mail.Body != null)
    {
    mail.Body = mail.Body.Replace(“”, emailMessage.Name);
    mail.Body = mail.Body.Replace(“”, emailMessage.CompanyName);
    mail.Body = mail.Body.Replace(“”, emailMessage.Address);
    mail.Body = mail.Body.Replace(“”, emailMessage.City);
    mail.Body = mail.Body.Replace(“”, emailMessage.State);
    mail.Body = mail.Body.Replace(“”, emailMessage.PhoneNumber);
    mail.Body = mail.Body.Replace(“”, emailMessage.EmailToName);
    mail.Body = mail.Body.Replace(“”, emailMessage.Message);
    mail.Body = mail.Body.Replace(“”, emailMessage.Information);
    mail.Body = mail.Body.Replace(“”, emailMessage.Comment);
    }

    var smtp = new SmtpClient();
    smtp.Send(mail);
    }
    catch (Exception ex) {
    if ((ex.InnerException == null) == true) {
    dynamic responser = Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message);
    return responser;
    } else {
    dynamic responser = Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message);
    return responser;
    }
    }

    emailMessage.RtnID = 1;

    dynamic response = Request.CreateResponse(HttpStatusCode.Created, emailMessage);
    response.Headers.Location = new Uri(Request.RequestUri, string.Format(“customer/{0}”, emailMessage.RtnID));
    return response;
    }

    public string GetEmailBody()
    {
    string templatePath = System.Web.HttpContext.Current.Server.MapPath(“~/ContactForm.txt”);
    var sr = new StreamReader(templatePath);
    return sr.ReadToEnd();
    }
    }

  2. Thank you. Somehow the formatting of the code caused a problem. I have corrected it.

Leave a Reply

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