Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Simple AJAX/Web API SMS/Texting Service

5.00/5 (2 votes)
2 Jun 2015CPOL2 min read 16.7K   267  
Simple AJAX/ASP .NET Web API SMS/Texting Service

Introduction

I was recently tasked with developing a way of incorporating SMS/Texting into some of our applications. I wanted to develop this around a Web API service.

This is my first CodeProject post. I welcome any and all feedback.

Background

I wanted to develop a basic SMS/Texting service using Microsoft Web API and AJAX. This is a very basic demo. I still need to add exception handling and modify it to work within my corporate environment.

This is a C#/VS 2013 project.

Using the Code

The first thing to do is to create a new Web API project. I prefer to start with a clean slate. For this project, I simply chose a C# ASP.NET Web Application using the "Empty" template with Web API checked. As this is a simple demo, I went with the default, "No Authentication" option.

There are three critical files necessary:

  1. The Model
  2. The Controller
  3. The HTML file containing the ajax calls.

The Model

This is necessary in order to handle parameter binding as well as to conform to good programming practices. In keeping with the Microsoft convention, I created a new C# class file in the Models folder and named it  SMS.

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace RosterAPI.Models
{
     public class SMS
     {
         public string PhoneNumber { get; set; }
         public string Carrier { get; set; }
         public string Subject { get; set; }
         public string Message { get; set; }
     }
}

The Controller

Again, in keeping with Microsoft convention standards, I created a C# class in the Controllers folder and named it SMSController. The contoller has two methods: Post() and FormatSMS(). The basic idea is to pass the controller a 10-digit phone number, a cellular carrier, a subject, and the message. The controller will use SMTP to email the phone number's carrier's SMS system. In order to be able to use this example, you'll need access to an SMTP server.

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Mail;
using System.Web.Http;
using RosterAPI.Models;
namespace RosterAPI.Controllers
{
     public class SMSController : ApiController
     {
          private HttpResponseMessage _msg = null;
          public void Get() { }

          public HttpResponseMessage Post(SMS newSMS)
          {
               try
              {
                   MailMessage sms = new MailMessage();
                   sms.From = new MailAddress("youremailaddress@yourdomain.com");
                   sms.To.Add(FormatSMS(newSMS.PhoneNumber, newSMS.Carrier));
                   sms.Subject = newSMS.Subject.Trim();
                   sms.IsBodyHtml = false;
                   sms.Priority = MailPriority.Normal;
                   sms.Body = newSMS.Message.Trim();
                   SmtpClient smtp = new SmtpClient();
                   smtp.Host = "localhost";
                   smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                   smtp.Send(sms);
                   return Request.CreateResponse(HttpStatusCode.OK, "SMS Sent");
              }

              catch (Exception xcp)
              {
                 return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, xcp.Message);
              } 
     }
     private string FormatSMS(string ph, string carrier)
     {
                Dictionary<string, string> carriers = new Dictionary<string, string>();
                carriers.Add("att", "@txt.att.net");
                carriers.Add("cellularone", "@mobile.celloneusa.com");
                carriers.Add("comcast", "@comcastpcs.textmsg.com");
                carriers.Add("metropcs", "@mymetropcs.com");
                carriers.Add("sprint", "@messaging.sprintpcs.com");
                carriers.Add("tmobile", "@tmomail.net");
                carriers.Add("verizon", "@vtext.com");
               return ph.Trim() + carriers[carrier]; 
          }
     }
}

The View

The view is a simple HTML page. Since this is a Web API project and doesn't have a View folder, I went ahead and left this file in the project's root directory. The page uses Bootstrap, so you'll need to download it from getbootstrap.com.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="favicon.ico">
<title>TMT SMS Service</title>
<!-- Bootstrap core CSS -->
<link href="Bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="Bootstrap/css/signin.css" rel="stylesheet">
<!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<script src="Bootstrap/assets/js/ie-emulation-modes-warning.js"></script>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container" style="padding-top:400px">
<form class="form-signin">
<label for="textTel" class="sr-only">Phone Number</label>
<input type="text" id="txtTel" class="form-control" 
placeholder="Phone Number" required autofocus>
<label for="selCarrier" class="sr-only">Carrier</label>
<select id="selCarrier" class="form-control" required>
<option value="">Select A Carrier</option>
<option value="att">AT&T</option>
<option value="cellularone">Cellular One</option>
<option value="sprint">Sprint</option>
<option value="tmobile">T-Mobile</option>
<option value="verizon">Verizon</option>
</select>
<label for="txtMsg" class="sr-only">Message</label>
<textarea id="txtMsg" class="form-control" rows="3" 
placeholder="Message" required></textarea>
<br/>
<button class="btn btn-lg btn-primary btn-block" type="submit">
<span class="glyphicon glyphicon-envelope">lt;/span></button>
</form>
</div> <!-- /container -->
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="Bootstrap/assets/js/ie10-viewport-bug-workaround.js"></script>
<script src="Scripts/jquery-2.1.3.min.js"></script>
<script src="Scripts/sms.js"></script>
<script> 

(function () {

$(":submit").on('click', function () {
SMS = {
PhoneNumber: $('#txtTel').val(),
Carrier: $('#selCarrier').val(),
Subject: 'Message from TM Tools SMS Service',
Message: $('#txtMsg').val()
}
sendSMS(SMS, function (data) {
alert(data);
});
}); 
 
})(jQuery); 
 
</script>
</body>
</html>

Points of Interest

I hope this provides you with a good starting point. I know there's a lot more work I'm going to do with this including a log.

Happy coding everyone.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)