Click here to Skip to main content
11,713,456 members (84,629 online)
Click here to Skip to main content

Sending SMS using .NET

, 11 Jun 2007 CPL 256.4K 5 264
Rate this:
Please Sign up or sign in to vote.
This article covers some of the ways of sending SMS using .NET

Introduction

When do you want to send SMS via applications? There could be plethora of use cases for this. The simplest one is to validate a mobile number, and some of the complicated ones could involve sending an SMS after a huge workflow is complete or gone wrong. Let's find out ways to send SMS using C#/VB.NET.

Sending SMS

What are the ways in which one can send SMS?

  • Using a GSM modem:
    • Better when one wants to implement offline applications and a very small number of SMS go every minute, usually few 10s.
  • Using web service:
    • Better when it is an online application and a very few number of SMS go every minute, usually few 10s.
  • Using endpoints given by service the provider:
    • Better when the number of SMS exceeds a few 100s per minute. Service provider demands a commitment of at least 100,000 SMS per month.

Sending SMS via a webservice or endpoints is simplest. In contrast, sending SMS via GSM modem has a few additional steps to take care of. Let's understand each in detail.

Sending SMS via GSM modem

  1. First, find the best GSM modem that suits the needs. Specifications are available here.
  2. Understand the AT Command set required to communicate with the modem.
  3. Connect the modem to the computer according to the setup guide specified in the manual provided with the GSM modem. Sample connection details of the Maestro 20/100 modem can be found here. The connection settings explained are common for most GSM modems.
  4. Create a new Windows application or Web Application.
  5. Add a new class file with the name SMSCOMMS.
  6. Copy and paste the code given below into the class.

Coding with VB.NET

If you are using VB.NET for coding the application, you can use the class shared by Jeanred. Details are as follows:

Option Explicit On    

Imports System
Imports System.Threading
Imports System.ComponentModel
Imports System.IO.PortsPublic Class SMSCOMMS    

Private WithEvents SMSPort As SerialPort    

    Private SMSThread As Thread
    Private ReadThread As Thread
    Shared _Continue As Boolean = False
    Shared _ContSMS As Boolean = False
    Private _Wait As Boolean = False
    Shared _ReadPort As Boolean = False
    Public Event Sending(ByVal Done As Boolean)
    Public Event DataReceived(ByVal Message As String)    

    Public Sub New(ByRef COMMPORT As String)
        SMSPort = New SerialPort
        With SMSPort
            .PortName = COMMPORT
            .BaudRate = 9600
            .Parity = Parity.None
            .DataBits = 8
            .StopBits = StopBits.One
            .Handshake = Handshake.RequestToSend
                .DtrEnable = True
              .RtsEnable = True
            .NewLine = vbCrLf
        End With
        ReadThread = New Thread(AddressOf ReadPort)
        End Sub    

    Public Function SendSMS(ByVal CellNumber As String, 
        ByVal SMSMessage As String) As Boolean
        Dim MyMessage As String = Nothing
        'Check if Message Length <= 160
        If SMSMessage.Length <= 160 Then
            MyMessage = SMSMessage
        Else
              MyMessage = Mid(SMSMessage, 1, 160)
        End If
        If IsOpen = True Then
                SMSPort.WriteLine("AT+CMGS=" & CellNumber & vbCr)
                _ContSMS = False
                SMSPort.WriteLine(MyMessage & vbCrLf & Chr(26))
                _Continue = False
                RaiseEvent Sending(False)
        End If
    End Function    

    Private Sub ReadPort()
          Dim SerialIn As String = Nothing
        Dim RXBuffer(SMSPort.ReadBufferSize) As Byte
        Dim SMSMessage As String = Nothing
        Dim Strpos As Integer = 0
        Dim TmpStr As String = Nothing    

            While SMSPort.IsOpen = True
            If (SMSPort.BytesToRead <> 0) And (
                SMSPort.IsOpen = True) Then
                While SMSPort.BytesToRead <> 0
                    SMSPort.Read(RXBuffer, 0, SMSPort.ReadBufferSize)
                    SerialIn = 
                        SerialIn & System.Text.Encoding.ASCII.GetString(
                        RXBuffer)
                    If SerialIn.Contains(">") = True Then
                        _ContSMS = True
                    End If
                    If SerialIn.Contains("+CMGS:") = True Then
                        _Continue = True
                        RaiseEvent Sending(True)
                        _Wait = False
                        SerialIn = String.Empty
                        ReDim RXBuffer(SMSPort.ReadBufferSize)
                    End If
                End While
                RaiseEvent DataReceived(SerialIn)
                SerialIn = String.Empty
                ReDim RXBuffer(SMSPort.ReadBufferSize)
            End If
        End While
    End Sub    

    Public ReadOnly Property IsOpen() As Boolean
        Get
            If SMSPort.IsOpen = True Then
                IsOpen = True
            Else
                IsOpen = False
            End If
        End Get
    End Property    

    Public Sub Open()
        If IsOpen = False Then
            SMSPort.Open()
            ReadThread.Start()
        End If
    End Sub    

    Public Sub Close()
        If IsOpen = True Then
            SMSPort.Close()
        End If
    End Sub    

End Class

The above class exposes three functions: Open, SendSMS and Close. While creating the instance of the class, provide the port to which the modem is connected. In a Windows application, follow the steps below:

SMSEngine = New SMSCOMMS("COM1")
SMSEngine.Open()
SMSEngine.SendSMS("919888888888","SMS Testing")
SMSEngine.Close()

Coding with C#

The C# implementation of the code is as follows:

using System;
using System.Threading;
using System.ComponentModel;
using System.IO.Ports;   

public class SMSCOMMS
{
    private SerialPort SMSPort;
    private Thread SMSThread;
    private Thread ReadThread;
    public static bool _Continue = false;
    public static bool _ContSMS = false;
    private bool _Wait = false;
    public static bool _ReadPort = false;
    public delegate void SendingEventHandler(bool Done);
    public event SendingEventHandler Sending;
    public delegate void DataReceivedEventHandler(string Message);
    public event DataReceivedEventHandler DataReceived;    

    public SMSCOMMS(ref string COMMPORT)
    {
        SMSPort = new SerialPort();
        SMSPort.PortName = COMMPORT;
        SMSPort.BaudRate = 9600;
        SMSPort.Parity = Parity.None;
        SMSPort.DataBits = 8;
        SMSPort.StopBits = StopBits.One;
        SMSPort.Handshake = Handshake.RequestToSend;
        SMSPort.DtrEnable = true;
        SMSPort.RtsEnable = true;
        SMSPort.NewLine = System.Environment.NewLine;
        ReadThread = new Thread(
            new System.Threading.ThreadStart(ReadPort));
    }    

    public bool SendSMS(string CellNumber, string SMSMessage)
    {
        string MyMessage = null;
        //Check if Message Length <= 160
        if (SMSMessage.Length <= 160)
            MyMessage = SMSMessage;
        else
            MyMessage = SMSMessage.Substring(0, 160);
        if (IsOpen == true)
        {
            SMSPort.WriteLine("AT+CMGS=" + CellNumber + "r");
            _ContSMS = false;
                SMSPort.WriteLine(
                MyMessage + System.Environment.NewLine + (char)(26));
              _Continue = false;
            if (Sending != null)
                Sending(false);
        }
        return false;
    }    

    private void ReadPort()
    {
        string SerialIn = null;
        byte[] RXBuffer = new byte[SMSPort.ReadBufferSize + 1];
        string SMSMessage = null;
        int Strpos = 0;
        string TmpStr = null;
        while (SMSPort.IsOpen == true)
        {
            if ((SMSPort.BytesToRead != 0) & (SMSPort.IsOpen == true))
            {
                while (SMSPort.BytesToRead != 0)
                {
                    SMSPort.Read(RXBuffer, 0, SMSPort.ReadBufferSize);
                    SerialIn = 
                        SerialIn + System.Text.Encoding.ASCII.GetString(
                        RXBuffer);
                            if (SerialIn.Contains(">") == true)
                    {
                        _ContSMS = true;
                    }
                    if (SerialIn.Contains("+CMGS:") == true)
                    {
                        _Continue = true;
                        if (Sending != null)
                            Sending(true);
                        _Wait = false;
                        SerialIn = string.Empty;
                        RXBuffer = new byte[SMSPort.ReadBufferSize + 1];
                    }
                }
                if (DataReceived != null)
                    DataReceived(SerialIn);
                SerialIn = string.Empty;
                RXBuffer = new byte[SMSPort.ReadBufferSize + 1];
            }
        }
    }    

    public bool SendSMS(string CellNumber, string SMSMessage)
    {
        string MyMessage = null;
        if (SMSMessage.Length <= 160)
        {
            MyMessage = SMSMessage;
        }
        else
        {
            MyMessage = SMSMessage.Substring(0, 160);
        }
        if (IsOpen == true)
        {
            SMSPort.WriteLine("AT+CMGS=" + CellNumber + "r");
            _ContSMS = false;
                SMSPort.WriteLine(
                    MyMessage + System.Environment.NewLine + (char)(26));
              _Continue = false;
            if (Sending != null)
                Sending(false);
        }
        return false;
    }    

    public void Open()
    {
        if (IsOpen == false)
        {
            SMSPort.Open();
                ReadThread.Start();
        }
    }    

    public void Close()
    {
        if (IsOpen == true)
        {
            SMSPort.Close();
        }
    }    

}

Then use the code as below:

SMSEngine = new SMSCOMMS("COM1");
SMSEngine.Open();
SMSEngine.SendSMS("919888888888","THIS IS YOUR MESSAGE");
SMSEngine.Close();

Sending SMS via a webservice

Sending SMS via webservices, although not for real-time services, is a very cost-effective solution. There are lots of webservices and you should be able to find one by searching the web. There are free ones that are not so reliable. So, purchase SMS credits to send a limited number of SMS using a webservice. Here, the usage is very simple, as it is just consuming a webservice to send a number and message to a function. The Code Project sample is available at The Code Project.

Sending SMS via service provider endpoints

Sending SMS via service provider is also similar to using a webservice. Here, it may be a non-standard protocol or over HTTP. It differs from service provider to service provider. Some provide sample code that can be used for programming custom applications.

History

  • 1 June, 2007 -- Original version posted.
  • 11 June, 2007 -- Article edited and posted to the main CodeProject.com article base.

License

This article, along with any associated source code and files, is licensed under The Common Public License Version 1.0 (CPL)

Share

About the Author

PooranPrasad
India India
http://pooran.googlepages.com

You may also be interested in...

Comments and Discussions

 
QuestionStill has problem on Codes, Not working Pin
creatives.system31-Jul-12 2:06
membercreatives.system31-Jul-12 2:06 
Questionhi please solve this problem Pin
Aziz BUkhari24-Jul-12 10:35
memberAziz BUkhari24-Jul-12 10:35 
Questioni have trouble :( Pin
Aziz BUkhari24-Jul-12 10:25
memberAziz BUkhari24-Jul-12 10:25 
GeneralRe: i have trouble :( Pin
Member 930707327-Jul-12 14:22
memberMember 930707327-Jul-12 14:22 
Questionsending SMS from c# Pin
TamilarasiTest2-Apr-12 4:06
memberTamilarasiTest2-Apr-12 4:06 
Questionsend sms via mobile in c# Pin
namard7-Jan-12 1:27
membernamard7-Jan-12 1:27 
AnswerRe: send sms via mobile in c# Pin
namard7-Jan-12 1:33
membernamard7-Jan-12 1:33 
QuestionHi Pin
yuvaraj.m19922gmail22-Nov-11 18:13
memberyuvaraj.m19922gmail22-Nov-11 18:13 
Questionsms is not sending Pin
somendratiwari9-Nov-11 21:27
membersomendratiwari9-Nov-11 21:27 
QuestionSuggestion needed. Pin
Hema Bairavan13-Oct-11 20:45
memberHema Bairavan13-Oct-11 20:45 
Generalsa Pin
prashantish16-Sep-11 22:29
memberprashantish16-Sep-11 22:29 
Questionno response Pin
sundarpks31-Jul-11 23:59
membersundarpks31-Jul-11 23:59 
GeneralMy vote of 5 Pin
BrianBissell27-Jul-11 9:02
memberBrianBissell27-Jul-11 9:02 
Generalproblem with code Pin
dipon1232-May-11 10:21
memberdipon1232-May-11 10:21 
General"Then use the code as below" Pin
skymail524-Apr-11 5:36
memberskymail524-Apr-11 5:36 
GeneralMy vote of 5 Pin
SAKryukov13-Mar-11 12:22
memberSAKryukov13-Mar-11 12:22 
QuestionSending via Mobile Pin
IPECorp26-Aug-10 8:17
memberIPECorp26-Aug-10 8:17 
QuestionHow to connect through internet Pin
shaz001131-Jul-10 7:05
membershaz001131-Jul-10 7:05 
GeneralMessage Length Pin
Mairy13-Jul-10 22:17
memberMairy13-Jul-10 22:17 
GeneralMy vote of 5 Pin
rameshmsr12-Jul-10 2:49
memberrameshmsr12-Jul-10 2:49 
GeneralRe: My vote of 5 Pin
dipon1232-May-11 10:20
memberdipon1232-May-11 10:20 
Generalreceive sms Pin
mukuljain0073-May-10 2:48
membermukuljain0073-May-10 2:48 
Questionhaing problem in attending the code of c# Pin
ankurbhutani9-Nov-09 22:49
memberankurbhutani9-Nov-09 22:49 
AnswerRe: haing problem in attending the code of c# Pin
sreerejithss11-Aug-10 21:31
membersreerejithss11-Aug-10 21:31 
Generalusing wavecom modem Pin
bandi_satish7-May-09 19:58
memberbandi_satish7-May-09 19:58 
GeneralSMS sending and receiving problem Pin
55524-Feb-09 18:01
member55524-Feb-09 18:01 
AnswerRe: SMS sending and receiving problem Pin
Egor Serdtsev16-Apr-09 2:10
memberEgor Serdtsev16-Apr-09 2:10 
GeneralSMS sending and receiving problem Pin
55524-Feb-09 16:15
member55524-Feb-09 16:15 
GeneralRe: SMS sending and receiving problem Pin
Mairy13-Jul-10 21:04
memberMairy13-Jul-10 21:04 
GeneralVolume Equalizer Pin
sshakeerbaig23-Feb-09 17:07
membersshakeerbaig23-Feb-09 17:07 
GeneralPLEASE Pin
Nega adugna29-Dec-08 19:41
memberNega adugna29-Dec-08 19:41 
GeneralI failed what shall i do Pin
Nega adugna24-Dec-08 0:38
memberNega adugna24-Dec-08 0:38 
Generalwould you help me Pin
niktana1-Sep-08 5:53
memberniktana1-Sep-08 5:53 
GeneralHelp me please... in Sending SMS thru' .net Pin
Madhava Manikandan24-Jul-08 1:03
memberMadhava Manikandan24-Jul-08 1:03 
Questionusing Netbean IDE 5.0 to program Pin
wwlong15-Jun-08 15:49
memberwwlong15-Jun-08 15:49 
NewsRe: using Netbean IDE 5.0 to program Pin
PooranPrasad2-Jul-08 1:50
memberPooranPrasad2-Jul-08 1:50 
QuestionI need help to receive SMS from my computer! Pin
jennina27-May-08 19:26
memberjennina27-May-08 19:26 
GeneralRe: I need help to receive SMS from my computer! Pin
wwlong15-Jun-08 15:59
memberwwlong15-Jun-08 15:59 
QuestionSending and receiving SMS using only a cable Pin
jennina27-May-08 19:21
memberjennina27-May-08 19:21 
GeneralA better option to send an SMS message with a GSM modem Pin
William Ike8-Mar-08 21:31
memberWilliam Ike8-Mar-08 21:31 
Generalhelp for project. Pin
swapnilrkadam26-Feb-08 20:40
memberswapnilrkadam26-Feb-08 20:40 
GeneralError:The I/O operation has been aborted because of either a thread exit or an application request. Pin
Nadia v D17-Jan-08 4:57
memberNadia v D17-Jan-08 4:57 
GeneralBuild problems Pin
_Jon_6-Nov-07 5:20
member_Jon_6-Nov-07 5:20 
QuestionCould you help? THanks Pin
jaski16-Oct-07 6:14
memberjaski16-Oct-07 6:14 
AnswerRe: Could you help? THanks Pin
PooranPrasad2-Jul-08 1:52
memberPooranPrasad2-Jul-08 1:52 
QuestionSend Status Pin
ikkaz8-Oct-07 21:56
memberikkaz8-Oct-07 21:56 
QuestionIs it suitable for any GSM mobile phones? Pin
ThalaChinna8-Oct-07 7:32
memberThalaChinna8-Oct-07 7:32 
QuestionHow to send SMS to specific application on mobile Pin
amit_lole2-Oct-07 21:58
memberamit_lole2-Oct-07 21:58 
GeneralRe: How to send SMS to specific application on mobile Pin
Member 43024701-Apr-08 3:27
memberMember 43024701-Apr-08 3:27 
GeneralRe: How to send SMS to specific application on mobile Pin
amit_lole1-Apr-08 22:35
memberamit_lole1-Apr-08 22:35 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150819.1 | Last Updated 11 Jun 2007
Article Copyright 2007 by PooranPrasad
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid