Click here to Skip to main content
Click here to Skip to main content

.NET Phone Communication Library Part IV - Receive SMS

By , 10 Dec 2006
 

Sample Image - phonesmsrecv.jpg

Introduction

In part II of the article, I showed you how to send SMS using a GSM modem which is built into your mobile phone. However, I did not show you how to detect incoming SMS. To detect new SMS received, it is a bit tricky as different mobile phones from different manufacturers may need different configurations. In this article, I am going to show you how to detect new SMS using the open source atSMS library.

How It Works

In order to detect incoming SMS, you must use the "AT+CNMI" command to set the new message indication to the terminal equipment (TE).

For the "+CNMI" command, the values are in the format of mode,mt,bm,ds,bfr. In order to receive SMS, mt must be 1. For other values, different handsets may require different values to be set. By default, the atSMS library sets mode and mt to 1 which should be sufficient for most handsets. However, you can always use the CheckATCommands function to check your phone supported values.

Take note also that during my testing, it was noticed that for certain Nokia phones only, Class 2 SMS can be detected. For newer models of Nokia phones, e.g., N70, N80, the "+CNMI" is not supported, and you have no way of detecting incoming SMS.

The Code

By setting NewMessageIndication to True, and if your phone supports "+CNMI", the NewMessageReceived event should be raised.

Imports ATSMS

Public Class MainForm

    Private WithEvents oGsmModem As New GSMModem

    Private Sub MainForm_Load(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles MyBase.Load
        CheckForIllegalCrossThreadCalls = False
    End Sub

    
    Private Sub btnPhone_Click(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles btnConnect.Click

        If cboComPort.Text = String.Empty Then
            MsgBox("COM Port must be selected", MsgBoxStyle.Information)
            Return
        End If

        oGsmModem.Port = cboComPort.Text

        If cboBaudRate.Text <> String.Empty Then
            oGsmModem.BaudRate = Convert.ToInt32(cboBaudRate.Text)
        End If

        If cboDataBit.Text <> String.Empty Then
            oGsmModem.DataBits = Convert.ToInt32(cboDataBit.Text)
        End If

        If cboStopBit.Text <> String.Empty Then
            Select Case cboStopBit.Text
                Case "1"
                    oGsmModem.StopBits = Common.EnumStopBits.One
                Case "1.5"
                    oGsmModem.StopBits = Common.EnumStopBits.OnePointFive
                Case "2"
                    oGsmModem.StopBits = Common.EnumStopBits.Two
            End Select
        End If

        If cboFlowControl.Text <> String.Empty Then
            Select Case cboFlowControl.Text
                Case "None"
                    oGsmModem.FlowControl = Common.EnumFlowControl.None
                Case "Hardware"
                    oGsmModem.FlowControl = Common.EnumFlowControl.RTS_CTS
                Case "Xon/Xoff"
                    oGsmModem.FlowControl = Common.EnumFlowControl.Xon_Xoff
            End Select
        End If

        Try
            oGsmModem.Connect()
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical)
            Return
        End Try

        Try
            oGsmModem.NewMessageIndication = True
        Catch ex As Exception

        End Try

        btnSendMsg.Enabled = True
        btnSendClass2Msg.Enabled = True
        btnCheckPhone.Enabled = True
        btnDisconnect.Enabled = True

        MsgBox("Connected to phone successfully !", MsgBoxStyle.Information)

    End Sub


    Private Sub btnDisconnect_Click(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles btnDisconnect.Click
        Try
            oGsmModem.Disconnect()
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical)
        End Try

        btnSendMsg.Enabled = False
        btnSendClass2Msg.Enabled = False
        btnCheckPhone.Enabled = False
        btnDisconnect.Enabled = False
        btnConnect.Enabled = True

    End Sub

   
    Private Sub btnSendMsg_Click(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles btnSendMsg.Click
        If txtPhoneNumber.Text.Trim = String.Empty Then
            MsgBox("Phone number must not be empty", MsgBoxStyle.Critical)
            Return
        End If

        If txtMsg.Text.Trim = String.Empty Then
            MsgBox("Phone number must not be empty", MsgBoxStyle.Critical)
            Return
        End If

        Try
            Dim msg As String = txtMsg.Text.Trim
            Dim msgNo As String
            If StringUtils.IsUnicode(msg) Then
                msgNo = oGsmModem.SendSMS(txtPhoneNumber.Text, msg, _
                        Common.EnumEncoding.Unicode_16Bit)
            Else
                msgNo = oGsmModem.SendSMS(txtPhoneNumber.Text, msg, _
                        Common.EnumEncoding.GSM_Default_7Bit)
            End If
            MsgBox("Message is sent. Reference no is " & msgNo, _
                    MsgBoxStyle.Information)
        Catch ex As Exception
            MsgBox(ex.Message & ". Make sure your SIM memory" & _ 
                   " is not full.", MsgBoxStyle.Critical)
        End Try

        'Try
        '    Dim storages() As Storage = oGsmModem.GetStorageSetting
        '    Dim i As Integer
        '    txtStorage.Text = String.Empty
        '    For i = 0 To storages.Length - 1
        '        Dim storage As Storage = storages(i)
        '        txtStorage.Text += storage.Name & "(" & _
        '          storage.Used & "/" & storage.Total & "), "
        '    Next
        'Catch ex As Exception
        '    txtStorage.Text = "Not supported"
        'End Try
    End Sub

    Private Sub btnSendClass2Msg_Click(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles btnSendClass2Msg.Click
        If txtPhoneNumber.Text.Trim = String.Empty Then
            MsgBox("Phone number must not be empty", MsgBoxStyle.Critical)
            Return
        End If

        If txtMsg.Text.Trim = String.Empty Then
            MsgBox("Phone number must not be empty", MsgBoxStyle.Critical)
            Return
        End If

        Try
            Dim msg As String = txtMsg.Text.Trim
            Dim msgNo As String
            If StringUtils.IsUnicode(msg) Then
                msgNo = oGsmModem.SendSMS(txtPhoneNumber.Text, msg, _
                        Common.EnumEncoding.Unicode_16Bit)
            Else
                msgNo = oGsmModem.SendSMS(txtPhoneNumber.Text, msg, _
                        Common.EnumEncoding.Class2_7_Bit)
            End If
            MsgBox("Message is sent. Reference no is " & msgNo, _
                    MsgBoxStyle.Information)
        Catch ex As Exception
            MsgBox(ex.Message & ". Make sure your SIM memory is not full.", _
                   MsgBoxStyle.Critical)
        End Try

        'Try
        '    Dim storages() As Storage = oGsmModem.GetStorageSetting
        '    Dim i As Integer
        '    txtStorage.Text = String.Empty
        '    For i = 0 To storages.Length - 1
        '        Dim storage As Storage = storages(i)
        '        txtStorage.Text += storage.Name & "(" & _
        '             storage.Used & "/" & storage.Total & "), "
        '    Next
        'Catch ex As Exception
        '    txtStorage.Text = "Not supported"
        'End Try
    End Sub


    Private Sub oGsmModem_NewMessageReceived(ByVal e As _
            ATSMS.NewMessageReceivedEventArgs) Handles _
            oGsmModem.NewMessageReceived
        txtMsg.Text = "Message from " & e.MSISDN & ". Message - " & _
                      e.TextMessage & ControlChars.CrLf
    End Sub

    Private Sub btnCheckPhone_Click(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles btnCheckPhone.Click
        MsgBox("Going to analyze your phone. It may take a while", _
                MsgBoxStyle.Information)
        oGsmModem.CheckATCommands()
        If oGsmModem.ATCommandHandler.Is_SMS_Received_Supported Then
            MsgBox("Your phone is able to receive SMS. Message " & _ 
                   "indication command is " & _
                   oGsmModem.ATCommandHandler.MsgIndication, _
                   MsgBoxStyle.Information)
            oGsmModem.NewMessageIndication = True
        Else
            MsgBox("Sorry. Your phone cannot receive SMS", _
                   MsgBoxStyle.Information)
        End If
    End Sub
End Class

In the next article, I will show you how to send vCard, vCalendar, and WAP Push messages using the atSMS library.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

twit88
Web Developer
Malaysia Malaysia
Member
A programmer for a long time, and still learning everyday.
 
A supporter for open source solutions, and have written quite a few open source software both in .NET and Java.
 
Homepage
http://twit88.com/home
 
Blog
http://twit88.com/blog

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionnice one and very good perfect connectionmemberAlvinApolinario4 Mar '13 - 22:38 
ilove you very much i need this badly man... nice one and very good perfect connectionThumbs Up | :thumbsup:
Questionthe codememberAngustong16 Jan '13 - 22:10 
there is an error for import ATMS. how to solve this error?
Questionobject reference not set to an instance of objectmake sure your sim memory is not fullmembervinodpii23 Oct '11 - 22:28 
object reference not set to an instance of objectmake sure your sim memory is not full.iam getting this error.Please help me out its urgent
QuestionHELP: send LongSMS [modified]memberrember2417 Apr '11 - 22:17 
Hello sir. this article is great and i really appreciate it. my question is, i want to send and recieve a longSMS also but i dont know from which part of the code will i change in order for me to send/recieve longSMS.. thanks alot! Laugh | :laugh:

modified on Saturday, May 7, 2011 3:59 AM

GeneralMy vote of 5memberleesong13 Feb '11 - 1:30 
IMBA tutorial I love it!
Generalhello i have some suguessionsmemberleesong12 Feb '11 - 23:46 
i hope you can put default settings to dropdownlist comboboxes
how to add, just put cbo.selecteditem = cbo.items(<index>) for default settings
thanks =D
 
btw i don't know how to setup Confused | :confused:
 
Making Youtube Video Downloader Using VB.NET!
QuestionDelete code does not workgrouphkkarri14 Sep '10 - 22:26 
Hi there,
 
The above code does not work for me.
 
At messagestore.refresh() i get an error which says unable to get the data
 
Messagestore.count is always zero where as messagememory shows the correct count of the messages in the sim.
 
Pl help.
 
Thanks and Regards
Generalmanage and get delivery messegememberAhmad Aghili2 Sep '10 - 1:39 
hi . i need to get delivery messege. but i can't get good slution. any body can help me?
 
if you have good code send that for me.
ahmad_aghili@yahoo.com
the best job is software developing.

Generalsending option not working [modified]memberteninfotech8 Aug '10 - 20:27 
Hi,
Receive message option is working fine but sending not working.
 
I am using serial port connection.
 
After click on 'send Message' or 'Send Class 2 Message' it shows me message that, "Message is Sent. The Reference no. is"
 
But does not show any reference no.
 
Can also reply to support@teninfotech.com

modified on Tuesday, August 10, 2010 1:36 AM

GeneralError Sending SMS Message. Unknown exception is sending command. Make sure your SIM Memory is not fullmemberMember 401217019 Feb '10 - 18:28 
When an Execute the project i got this error message...
 
Error Sending SMS Message. Unknown exception is sending command. Make sure your SIM Memory is not full
Arul

GeneralRe: Error Sending SMS Message. Unknown exception is sending command. Make sure your SIM Memory is not fullmemberalshaqsi21 Mar '10 - 14:40 
I got the same error msg!!!! Any help?
GeneralRe: Error Sending SMS Message. Unknown exception is sending command. Make sure your SIM Memory is not fullmemberArieljays8 Jan '13 - 9:39 
how to solve this problem?
Questionhow to raise event for Newmessagereceivedmemberskinny869 Feb '10 - 20:58 
Need help on raising the event for new message received!
Tried RaiseEvent but vb said that its not an event of the form. Please help!
GeneralSIR I NEED YOUR HELPmembermark aldrin reyes28 Dec '09 - 22:28 
I'm having a problem in receiving and deleting..
 
I'm using N3230
 
My phone can send perfectly. but cannot detect the incoming messages..
 
Please email me some solutions if possible..
 
tnx
Questionhow to receive sms ?????memberumerufm4 Jul '09 - 21:16 
hi
Confused | :confused: plz tell me how we receive the sms through ATSMS
lib.
can u provide me the documation of the ATSMS
i try to fine but..........
plz reply Smile | :) m waiting for ur ANS
GeneralRe:ATSMS Lib 1.0.0.5membermanyara8 May '09 - 2:19 
Hi, there!
I'm Mohamed Kassimu, software developer with .net framework.
I tried to use the ATSMS.dll V1.0.0.5, but I fail to receive SMS when I use oGSM_newmassageReceived event.
How can I do in order to solve that?
 
Thanks.
 
Manyara.M.K.S

GeneralRe:ATSMS Lib 1.0.0.5membervan_walkman16 Jun '09 - 17:41 
Me too can't receive the message and display. Anyone out there solved it?
GeneralRe:ATSMS Lib 1.0.0.5memberCarlsoft8 Dec '09 - 14:24 
version 1.0.0 works fine with sending/receiving ^_^
Questioni need read all sms from our ATSMS .dll if its possiblememberMurugan_vdm21 Nov '08 - 21:25 
Hi,
 
Its good software for send sms. but its not delete automatically of the outbox. and i need read all message from mobile if its possible in our .dll file.
Questionhow to read sms from sim via gsm modemmemberraju_cuet23 Jul '08 - 23:31 
suppose i send a sms to a sim connected to a gsm modem.how can i read sms from inbox in java platform
Questionwant to send sms through phone memory not by sim....... [modified]memberhpindia23 Jul '08 - 2:34 
Hi all,
 
As i send sms it send through SIM memory and others will received in SIM memory. so can some one guide me how to send sms through phone memory so that other one get in phone memory...Confused | :confused:
 
the error message it show is "SIM Memory is Full" on both side sender / receiver and some times the receiver not received sms.
 
I am using nokia 6610i and 6070 with dku5 data cable...
 
its urgent...
 
thanks in advance...Rose | [Rose]
 
modified on Wednesday, July 23, 2008 8:43 AM

Generalunreadable text in receive textmembereclkq15 Apr '08 - 10:08 
what happen to my receive message from my friends...the real text is my friends sent me was "hello" but in the ATSMS show me this "??".
Who can give me a proper solution?
this is the coding i using to retrieve the message :
 
Private Sub oGsmModem_NewMessageReceived(ByVal e As ATSMS.NewMessageReceivedEventArgs) Handles oGsmModem.NewMessageReceived
txtMsg.Text = "Received msg from " & e.MSISDN & ControlChars.CrLf & e.TextMessage & ControlChars.CrLf & e.Timestamp & ControlChars.CrLf

End Sub

 
Pls contact me a.s.a.p
eclkq@yahoo.co.uk
thanks..
Generalcode for receive sms using gsm modem that connect to com portmembershee_dee868 Apr '08 - 16:16 
i'm the beginner in vb.net so i want to know how to receive sms using gsm modem that connnect to com port
gsm modem is detect at com 3 and i have been using hyper terminal an change at+cnmi=2,2,0,0,0 and it's said ok
by using rs232 serial com software it's detect the msg receive, but it show
 
+CMT: "REC UNREAD"'".....
test
 

so, the really msg that i want is at the second line of the msg shown.
so anyone can help me how to cut the delete the first line of the msg,and how to take the certain character to be display..
please...
Generaldeleting Inboxmemberk.Daniel22 Feb '08 - 17:37 
some one plz help me how to delete Inbox in phone... im un known to use 'oGsmModem.AutoDeleteNewMessage = True
'ATSMS.ATHandler.CMGD_COMMAND = "6,4"
 
plz help me...... im in peak time to submit my project.........
my mail id : daniel_praveen_kumar@yahoo.co.in
Smile | :)
 
daniel
QuestionHow to refresh New messagesmembernteng149 Jan '08 - 17:05 
btw I would like to say thank you to mpdesign and the creator of this ATSMS.dll
 
Dim msgstore As MessageStore = oPhone.MessageStore
oPhone.MessageMemory = EnumMessageMemory.PHONE
msgstore.Refresh()
 

'by default the "msgstore.Refresh()" retrieves ALLMessages (new, read, unsent, sent)
 
how do i set the "msgstore.Refresh" to new messages only?
 
do you have an idea? is it about messageType enum something?

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 10 Dec 2006
Article Copyright 2006 by twit88
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid