Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9251673
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T10:45:40+00:00 2026-06-18T10:45:40+00:00

I am able to send an sms from computer to mobile, but i am

  • 0

I am able to send an sms from computer to mobile, but i am not able to send multiple sms from pc.
This code is running successfully, i am sending message through AT Commands, i have searched google and even in stackoverflow, the information given is not matching with my requirements, so i am writing the code below, if you can give me some suggestions, please tell me. If any additional questions you want to ask me then do let me know please.

SMSForm.cs file

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.IO.Ports;
using Queue.Classes;

namespace Queue
{
public partial class SmsForm : Form
{
    public SmsForm()
    {
        InitializeComponent();
    }
    #region Private Variables

    SerialPort port = new SerialPort();
    clsSMS objclsSMS = new clsSMS();
    ShortMessageCollection objShortMessageCollection = new ShortMessageCollection();
    #endregion

    #region Private Methods

    #region Write StatusBar
    private void WriteStatusBar(string status)
    {

            statusBar1.Text = "Message: " + status;


    }
    #endregion

    #endregion



    private void btnOK_Click(object sender, EventArgs e)
    {
        try
        {
            //Open communication port 
            this.port = objclsSMS.OpenPort(this.cboPortName.Text, Convert.ToInt32(this.cboBaudRate.Text), Convert.ToInt32(this.cboDataBits.Text), Convert.ToInt32(this.txtReadTimeOut.Text), Convert.ToInt32(this.txtWriteTimeOut.Text));

            if (this.port != null)
            {
                this.gboPortSettings.Enabled = false;

                //MessageBox.Show("Modem is connected at PORT " + this.cboPortName.Text);
                this.statusBar1.Text = "Modem is connected at PORT " + this.cboPortName.Text;

                //Add tab pages
                this.tabSMSapplication.TabPages.Add(tabPage2);
                //  this.tabSMSapplication.TabPages.Add(tbReadSMS);
                //  this.tabSMSapplication.TabPages.Add(tbDeleteSMS);

                this.lblConnectionStatus.Text = "Connected at " + this.cboPortName.Text;
                this.btnDisconnect.Enabled = true;
            }

            else
            {
                //MessageBox.Show("Invalid port settings");
                this.statusBar1.Text = "Invalid port settings";
            }
        }
        catch (Exception ex)
        {
            ErrorLog(ex.Message);
        }
    }

    private void SmsForm_Load(object sender, EventArgs e)
    {
        try
        {
            #region Display all available COM Ports
            string[] ports = SerialPort.GetPortNames();

            // Add all port names to the combo box:
            foreach (string port in ports)
            {
                this.cboPortName.Items.Add(port);
            }
            #endregion

            //Remove tab pages
            this.tabSMSapplication.TabPages.Remove(tabPage2);

            //  this.tabSMSapplication.TabPages.Remove(tbReadSMS);
            //   this.tabSMSapplication.TabPages.Remove(tbDeleteSMS);

            this.btnDisconnect.Enabled = false;
        }
        catch (Exception ex)
        {
            ErrorLog(ex.Message);
        }
    }

    private void btnDisconnect_Click(object sender, EventArgs e)
    {
        try
        {
            this.gboPortSettings.Enabled = true;
            objclsSMS.ClosePort(this.port);

            //Remove tab pages
            this.tabSMSapplication.TabPages.Remove(tabPage2);
            //    this.tabSMSapplication.TabPages.Remove(tbReadSMS);
            //    this.tabSMSapplication.TabPages.Remove(tbDeleteSMS);

            this.lblConnectionStatus.Text = "Not Connected";
            this.btnDisconnect.Enabled = false;

        }
        catch (Exception ex)
        {
            ErrorLog(ex.Message);
        }
    }




    #region Error Log
    public void ErrorLog(string Message)
    {
        StreamWriter sw = null;

        try
        {
            WriteStatusBar(Message);

            string sLogFormat = DateTime.Now.ToShortDateString().ToString() + " " + DateTime.Now.ToLongTimeString().ToString() + " ==> ";
            //string sPathName = @"E:\";
            string sPathName = @"SMSapplicationErrorLog_";

            string sYear = DateTime.Now.Year.ToString();
            string sMonth = DateTime.Now.Month.ToString();
            string sDay = DateTime.Now.Day.ToString();

            string sErrorTime = sDay + "-" + sMonth + "-" + sYear;

            sw = new StreamWriter(sPathName + sErrorTime + ".txt", true);

            sw.WriteLine(sLogFormat + Message);
            sw.Flush();

        }
        catch (Exception ex)
        {
            ErrorLog(ex.ToString());
        }
        finally
        {
            if (sw != null)
            {
                sw.Dispose();
                sw.Close();
            }
        }

    }
    #endregion 

    private void sendsms_Click(object sender, EventArgs e)
    {
        try
        {

            if (objclsSMS.sendMsg(this.port, this.sim.Text, this.mssging.Text))
            {
                //MessageBox.Show("Message has sent successfully");
                this.statusBar1.Text = "Message has sent successfully";
            }
            else
            {
                //MessageBox.Show("Failed to send message");
                this.statusBar1.Text = "Failed to send message";
            }

        }
        catch (Exception ex)
        {
            ErrorLog(ex.Message);
        }
    }


}
}

This is the class for Sending SMS

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Threading;
using System.Text.RegularExpressions;

namespace Queue.Classes
{
 public class clsSMS
 {
    #region Open and Close Ports
    //Open Port
    public SerialPort OpenPort(string p_strPortName, int p_uBaudRate, int p_uDataBits, int p_uReadTimeout, int p_uWriteTimeout)
    {
        receiveNow = new AutoResetEvent(false);
        SerialPort port = new SerialPort();

        try
        {
            port.PortName = p_strPortName;                 //COM1
            port.BaudRate = p_uBaudRate;                   //9600
            port.DataBits = p_uDataBits;                   //8
            port.StopBits = StopBits.One;                  //1
            port.Parity = Parity.None;                     //None
            port.ReadTimeout = p_uReadTimeout;             //300
            port.WriteTimeout = p_uWriteTimeout;           //300
            port.Encoding = Encoding.GetEncoding("iso-8859-1");
            port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
            port.Open();
            port.DtrEnable = true;
            port.RtsEnable = true;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return port;
    }

    //Close Port
    public void ClosePort(SerialPort port)
    {
        try
        {
            port.Close();
            port.DataReceived -= new SerialDataReceivedEventHandler(port_DataReceived);
            port = null;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    #endregion

    //Execute AT Command
    public string ExecCommand(SerialPort port, string command, int responseTimeout, string errorMessage)
    {
        try
        {

            port.DiscardOutBuffer();
            port.DiscardInBuffer();
            receiveNow.Reset();
            port.Write(command + "\r");

            string input = ReadResponse(port, responseTimeout);
            if ((input.Length == 0) || ((!input.EndsWith("\r\n> ")) && (!input.EndsWith("\r\nOK\r\n"))))
                throw new ApplicationException("No success message was received.");
            return input;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    //Receive data from port
    public void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        try
        {
            if (e.EventType == SerialData.Chars)
            {
                receiveNow.Set();
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    public string ReadResponse(SerialPort port, int timeout)
    {
        string buffer = string.Empty;
        try
        {
            do
            {
                if (receiveNow.WaitOne(timeout, false))
                {
                    string t = port.ReadExisting();
                    buffer += t;
                }
                else
                {
                    if (buffer.Length > 0)
                        throw new ApplicationException("Response received is incomplete.");
                    else
                        throw new ApplicationException("No data received from phone.");
                }
            }
            while (!buffer.EndsWith("\r\nOK\r\n") && !buffer.EndsWith("\r\n> ") && !buffer.EndsWith("\r\nERROR\r\n"));
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return buffer;
    }

    #region Count SMS
    public int CountSMSmessages(SerialPort port)
    {
        int CountTotalMessages = 0;
        try
        {

            #region Execute Command

            string recievedData = ExecCommand(port, "AT", 300, "No phone connected at ");
            recievedData = ExecCommand(port, "AT+CMGF=1", 300, "Failed to set message format.");
            String command = "AT+CPMS?";
            recievedData = ExecCommand(port, command, 1000, "Failed to count SMS message");
            int uReceivedDataLength = recievedData.Length;

            #endregion

            #region If command is executed successfully
            if ((recievedData.Length >= 45) && (recievedData.StartsWith("AT+CPMS?")))
            {

                #region Parsing SMS
                string[] strSplit = recievedData.Split(',');
                string strMessageStorageArea1 = strSplit[0];     //SM
                string strMessageExist1 = strSplit[1];           //Msgs exist in SM
                #endregion

                #region Count Total Number of SMS In SIM
                CountTotalMessages = Convert.ToInt32(strMessageExist1);
                #endregion

            }
            #endregion

            #region If command is not executed successfully
            else if (recievedData.Contains("ERROR"))
            {

                #region Error in Counting total number of SMS
                string recievedError = recievedData;
                recievedError = recievedError.Trim();
                recievedData = "Following error occured while counting the message" + recievedError;
                #endregion

            }
            #endregion

            return CountTotalMessages;

        }
        catch (Exception ex)
        {
            throw ex;
        }

    }
    #endregion

    #region Read SMS

    public AutoResetEvent receiveNow;

    public ShortMessageCollection ReadSMS(SerialPort port, string p_strCommand)
    {

        // Set up the phone and read the messages
        ShortMessageCollection messages = null;
        try
        {

            #region Execute Command
            // Check connection
            ExecCommand(port, "AT", 300, "No phone connected");
            // Use message format "Text mode"
            ExecCommand(port, "AT+CMGF=1", 300, "Failed to set message format.");
            // Use character set "PCCP437"
            ExecCommand(port, "AT+CSCS=\"PCCP437\"", 300, "Failed to set character set.");
            // Select SIM storage
            ExecCommand(port, "AT+CPMS=\"SM\"", 300, "Failed to select message storage.");
            // Read the messages
            string input = ExecCommand(port, p_strCommand, 5000, "Failed to read the messages.");
            #endregion

            #region Parse messages
            messages = ParseMessages(input);
            #endregion

        }
        catch (Exception ex)
        {
            throw ex;
        }

        if (messages != null)
            return messages;
        else
            return null;

    }
    public ShortMessageCollection ParseMessages(string input)
    {
        ShortMessageCollection messages = new ShortMessageCollection();
        try
        {
            Regex r = new Regex(@"\+CMGL: (\d+),""(.+)"",""(.+)"",(.*),""(.+)""\r\n(.+)\r\n");
            Match m = r.Match(input);
            while (m.Success)
            {
                ShortMessage msg = new ShortMessage();
                //msg.Index = int.Parse(m.Groups[1].Value);
                msg.Index = m.Groups[1].Value;
                msg.Status = m.Groups[2].Value;
                msg.Sender = m.Groups[3].Value;
                msg.Alphabet = m.Groups[4].Value;
                msg.Sent = m.Groups[5].Value;
                msg.Message = m.Groups[6].Value;
                messages.Add(msg);

                m = m.NextMatch();
            }

        }
        catch (Exception ex)
        {
            throw ex;
        }
        return messages;
    }

    #endregion

    #region Send SMS

    static AutoResetEvent readNow = new AutoResetEvent(false);

    public bool sendMsg(SerialPort port, string PhoneNo, string Message)
    {
        bool isSend = false;

        try
        {

            string recievedData = ExecCommand(port, "AT", 300, "No phone connected");
            recievedData = ExecCommand(port, "AT+CMGF=1", 300, "Failed to set message format.");
            String command = "AT+CMGS=\"" + PhoneNo + "\"";
            recievedData = ExecCommand(port, command, 300, "Failed to accept phoneNo");
            command = Message + char.ConvertFromUtf32(26) + "\r";
            recievedData = ExecCommand(port, command, 3000, "Failed to send message"); //3 seconds
            if (recievedData.EndsWith("\r\nOK\r\n"))
            {
                isSend = true;
            }
            else if (recievedData.Contains("ERROR"))
            {
                isSend = false;
            }
            return isSend;
        }
        catch (Exception ex)
        {
            throw ex;
        }

    }
    static void DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        try
        {
            if (e.EventType == SerialData.Chars)
                readNow.Set();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    #endregion



  }
 }

This is the another class for get and set:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Threading;
using System.Text.RegularExpressions;

namespace Queue.Classes
{
public class ShortMessage
{
    #region Private Variables
    private string index;
    private string status;
    private string sender;
    private string alphabet;
    private string sent;
    private string message;
    #endregion

    #region Public Properties
    public string Index
    {
        get { return index; }
        set { index = value; }
    }
    public string Status
    {
        get { return status; }
        set { status = value; }
    }
    public string Sender
    {
        get { return sender; }
        set { sender = value; }
    }
    public string Alphabet
    {
        get { return alphabet; }
        set { alphabet = value; }
    }
    public string Sent
    {
        get { return sent; }
        set { sent = value; }
    }
    public string Message
    {
        get { return message; }
        set { message = value; }
    }
    #endregion

}

public class ShortMessageCollection : List<ShortMessage>
{
}
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T10:45:41+00:00Added an answer on June 18, 2026 at 10:45 am

    I would recommend using GSMCOMM .NET library for this purpose
    http://www.scampers.org/steve/sms/libraries.htm

    or if you have nuget
    http://nuget.org/packages/GSMComm/

    This managed library would suit for your purpose and provide you with an easy to use api, so I recommend going with it and trying it for your use.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am not able to send publish message via kaazing javascript AMPQ library. Below
I am able to read SMS in Android from this:- phonesms = new ArrayList<String>();
I am working on a sms application. I am able to send a message
I want to send / receive sms using AT commands from my computer to
I am able to encrypt an SMS and send it from one simulator (Android
I am not able to send email from my yahoo id using Java mail
I am able to send a single SMS on BlackBerry, but when I try
I finally got my app to be able to send text messages (SMS), but
I'm able to send messages from Java to Websphere MQ on AS400 . If
I am able to send and receive message xmpp client and display them in

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.