Thursday, February 21, 2013

Use Twilio to send SMS in C#

For the previous example I've showed how to create a console application that runs every X seconds using Quartz.NET. So when the job is ran you might want to trigger a SMS alert in cases like, some processes are not running, DB no responding, HDD space running out.

For the SMS providers the 'hot' one would be Twilio, and you can get their helper library for C# at https://github.com/twilio/twilio-csharp#readme

You need to register and get your account id and token that you'll need for your API calls. I think there's a limited number of free SMS using the free trial account. If you upgrade then the SMS are charged per message. E.g. For Singapore where I'm located it's 2cents for sending a message to my carrier.

Sample code:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Twilio;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            //You should replace those in {} with your actual sid, token, twilio number and recipient phone
            //number

            TwilioRestClient client = new TwilioRestClient("{your account sid}", "{your account token}");

            var message = client.SendSmsMessage("your twilio number", "recipient's phone number", "Your message");
            Console.WriteLine(message.Sid);
        }
    }
}

No comments: