Wednesday, June 23, 2010

Sending SMS Via C#.Net

Introduction

The article will give you the very basic thing for sending SMS from your computer to any phone over GSM modem.

#region Private Declaration for the main thread
private Thread m_MailThread = null;
#endregion

#region Constructor
///
/// Constructor for InitializeComponent
///

public MySmsService()//Change MySmsService to your Service Class Name
{
InitializeComponent();
}
#endregion

#region OnStart Event of the service
protected override void OnStart(string[] args)
{
EvtlgSmsService.WriteEntry("MySmsService started!!");
if (m_MailThread == null)
m_MailThread = new Thread(new ThreadStart(SMSThread));
m_MailThread.Start();
}
#endregion

#region OnStop Event of the service
protected override void OnStop()
{
EvtlgSmsService.WriteEntry("MySmsService stopped !!.");
if (serialPort1.IsOpen)
serialPort1.Close();
m_MailThread.Abort();
}
#endregion

#region Sms Main thread
///
/// Sms main thread
///

private void SMSThread()
{
do
{
Thread.Sleep(30000);
SendSMS();
}
while (1 == 1);
}
#endregion

#region Send Sms function
///
/// SendSMS for sending the SMS
///

private void SendSMS()
{
SendSMS("+91000000000", "Hello This is a test message");
//+91 is the country code and followed by phone number
}
#endregion

#region Function for sending the Sms
///
/// Overloaded send SMS for sending the SMS
///
/// ///
private void SendSMS(String phoneNumber, String message)
{
try
{
if (!serialPort1.IsOpen)
serialPort1.Open();
serialPort1.Write("AT+CMGF=1" + (Char)13);
serialPort1.Write(String.Format("AT+CMGS=\"{0}\"" + (Char)13, phoneNumber));
serialPort1.Write(String.Format("{0}" + (Char)26 + (Char)13, message));
EvtlgSmsService.WriteEntry("SMS sent successfully");
}
catch (Exception e)
{
EvtlgSmsService.WriteEntry("SMS sending failed:" + e.Message);
}
}
#endregion
}

Just cut the above code and paste it in the Service class of your Windows service. Add a serial port component and an event log in the designer. Connect the GSM phone or modem to your computer. Check to which port the modem connects - that port should be given in the SerialPort1.portname. You should also make sure that your modem should support commands in the text mode. Check your modem by using the hyperterminal with the AT commands.

4 comments:

varaprasadreddy said...

here is the simple solution using way2sms / 160by2 accounts tested and working....

ClickHere for solution

summer smith said...

SEND ME MOBILE# +639192616111
MOBILE ALERTS

summer smith said...

send me mobile alert via sms +639192616111
verify my mobile# +639192616111

Abdus Salam said...

what is EvtlgSmsService? please give me the code of service

Post a Comment