Get Started!

Sending SMS

Sometime you'll need to send out SMS text message alerts from your applications / systems / website - here's how!

General

There's plenty of SMS service providers, this guide uses the service provided by TextLocal.com. There's no specific reason I selected thier service, well except they appear to use the UK network to send messages.

The API TextLocal expose has the endpoint:

  • http://api.txtlocal.com/send/

We can use WebClient to POST the values to the endpoint.

The C# Code

There are a range of parameters for sending messages, I've opted to create a group on the TextLocal site for the recipients of the Alert we're sending out. You can send to a single phone number if nessasary.

To authenticate on the service you either use a username / password combination or the API key, here we're using the API key.

using System;
using System.Text;
using System.Collections.Generic;
using System.Net;
using System.Web;
using System.Collections.Specialized;

namespace Net4orce.Examples {

  public static class SendSMS {

    private static readonly string apiKey = "API_KEY";
    private static readonly string groupId = "GROUP_ID";
    private static readonly string sender = "SENDER_NAME";
    private static readonly string apiEndPoint = "http://api.txtlocal.com/send/";

    /// Send, recives a string, msg, with the body of 
    /// the message.
    public static string Send(string msg) {

      // Encode the msg 
      var body = HttpUtility.UrlEncode(msg);

      // Create the payload to send to API
      var payload = new NameValueCollection(){
        {"apiKey" , apiKey},
        {"group_id" , groupId},
        {"message" , body},
        {"sender" , sender},
      };

      // Create a WebClient
      using ( var cli = new WebClient() ) {

        // Send the payload to the API
        byte[] buffer = cli.UploadValues(
          apiEndPoint, 
          payload
        );

        // Decode & return the result
        return Encoding.UTF8.GetString(buffer);

      }
    }
  }
}

That's it! Seriously, you can now send SMS messages using :

var result = SendSMS.Send("Hello, World");

Now, result contains some JSON with details about the number of SMS you have left to send etc, but I'll leave managing the result to you.