c# send SMS (Text)

c# send SMS (Text)


  You can send SMS using ASP.net web application. First you hunt for good SMS provider API. 
 
API should be capable of sending long messages more than 160 characters. 
 
It works with http Get Method. Below is the code snippet to deal with an API.

Add namespace called System.Net in your application to create objects of HttpWebRequest and HttpWebResponse

You need to setup communication between your web application and their SMS gateway.

Here are namespaces which you need to add in your asp.net web page.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Net;


Build your URL to post the SMS via web using http Get Method.


string msg =  HttpUtility.UrlEncode(txtMessage.Text);

//to encode the special characters and white spaces we need to use HttpUtility.UrlEncode

Lets post the Parameters to API.

Parameter Name: Value
1. UID:                xxx
2. PWD:               yyy
3. MSG:               Your+Encoded+message
5.MobileNumber:   91980098900
6. senderID:  SMS

Note*: sender id can be numeric or alphanumeric. It is a text, that will appear on end users handset once he receives the message.

In your case, parameters may be different. You need to read SMS Providers API document and find out what needs to be sent over HTTP get method.


protected void btnSend_Click(object sender, EventArgs e)
{

    //The final URL / api will be

    string API =
http://www.yoursmsprovider.com/smsAPI.php?UID=xxx&PWD=xxx&MSG=xxx+yyy+zzz&MobileNumber=9456546546;
        
       //uncomment below code, if it requires credentials to access your network via Proxy server and update appropriate fields
       //(IP address and  port )

       // WebProxy proxy = new WebProxy("192.168.1.100",3321);

       //uncomment below code if it requires credentials to access your network and update required

       //NetworkCredential credentials = new NetworkCredential("UserNAme","Password")
       //proxy.Credentials = credentials;


        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(api);

        // uncomment below line of code and tell your request to go via proxy server.

        //request.Proxy = proxy;

          HttpWebRequest request = (HttpWebRequest)WebRequest.Create(API);

        // setting up connection with web and posting vai GET method

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        // Returns httpwebresponse

           StreamReader reader = new StreamReader(response.GetResponseStream());

        // Read response stream


           Response.Write(reader.ReadToEnd());

}



You will get your transaction Id / or any unique code as a response. That can be used for retrieving the status of your SMS, whether it is sent or not.


Tags: