C# - Simple Wrapper for Nexmo Send SMS API call

By , 4/3/2013
(1 ratings)
Modified existing snippet to fix '&' in message, error text in response status class, and minor editing. (URL: http://dotnet-snippets.com/dns/send-sms-SID658.aspx)

Usage:
var nexmo = new NexmoAPIHelper("nexmo-user", "nexmo-pass") { Sender = "App1" };
var response = nexmo.SendSMS("44111222333", "Test one's \"Two & Three");


Original Author: Jan Welker
using System.Collections.Generic;
using System.Net;
using System.Web;
using System.Web.Script.Serialization;


namespace WindowsApp1
{
	class NexmoAPIHelper
	{
		string username, password;

		public string Sender { get; set; }


		public NexmoAPIHelper(string username, string password)
		{
			this.username = username;
			this.password = password;
			this.Sender = "Sender";
		}


		public NexmoResponse SendSMS(string to, string text)
		{
			var wc = new WebClient() { BaseAddress = "http://rest.nexmo.com/sms/json" };
			wc.QueryString.Add("username", HttpUtility.UrlEncode(username));
			wc.QueryString.Add("password", HttpUtility.UrlEncode(password));
			wc.QueryString.Add("from", HttpUtility.UrlEncode(Sender));
			wc.QueryString.Add("to", HttpUtility.UrlEncode(to));
			wc.QueryString.Add("text", HttpUtility.UrlEncode(text));
			return ParseSmsResponseJson(wc.DownloadString(""));
		}


		NexmoResponse ParseSmsResponseJson(string json)
		{
			json = json.Replace("-", "");  // hyphens are not allowed in in .NET var names
			return new JavaScriptSerializer().Deserialize<NexmoResponse>(json);
		}
	}


	public class NexmoResponse
	{
		public string Messagecount { get; set; }
		public List<NexmoMessageStatus> Messages { get; set; }
	}


	public class NexmoMessageStatus
	{
		public string MessageId { get; set; }
		public string To { get; set; }
		public string clientRef;
		public string Status { get; set; }
		public string ErrorText { get; set; }
		public string RemainingBalance { get; set; }
		public string MessagePrice { get; set; }
		public string Network;
	}
}

Tagged with nexmo, sms.

2 Comments

By Prasanna, 6/24/2014
Hi, I am new to VB.net. I get an error 'Key is not declared' in the below line:
Dim wc = New WebClient() With { Key.BaseAddress = "http://rest.nexmo.com/sms/json"}

Pls help. prasanna_lanka@yahoo.co.uk
By Koopakiller, 10/23/2014
@Prasanna
Remove the Key keyword from the translated version.
 

Log in, to comment!

Related Snippets