Android Code Snippet Send SMS/MMS using Twilio Rest API

You need to first create an account at Twilio.com and buy a phone number for around $1.00/month. Then using the below code you can send a text message to any desired number from the twilio number you bought at about $0.01 per SMS (around 125 characters).

Receiving an SMS to your Twilio number is a bit more complex because it requires a server post-back. I also have code to send MMS messages (send text + pictures), and code to receive MMS text/pictures messages and convert them into emails with attachments. I am available for hire if you need these additional abilities :)

Here is the SMS text sending code:

B4X:
Sub SendTwilioSMS(NumbertoSendto As String, MessageToSend As String)
    'This routine sends an SMS from your Twilio.com number to specified number (must include country code, but without leading "+")
    'This routine uses the new method that can send more then 160 characters (as an MMS)

    Dim j As HttpJob
    Dim URL As String         'url to post to
    Dim P As String           'url parameters
    Dim TUserName As String   '= your twilio username
    Dim TPassword As String   '= your twilio password
    Dim TNumber As String     '= your twilio number (ex. 12125551234 - must include country code, but without leading "+")

    URL = "https://api.twilio.com/2010-04-01/Accounts/" & TUserName & "/Messages"
    P = "From=%2B" & TNumber & "&To=%2B" & NumbertoSendto & "&Body=" & URLencode(MessageToSend)

    j.Initialize("", Me)
    j.Username = TUserName
    j.Password = TPassword
    j.PostString(URL,P)

    Wait For (j) JobDone(j As HttpJob)
    If j.Success Then
        Log(j.GetString)

        Msgbox("Message Sent OK!","SMS")
    Else
        Msgbox("There was an error sending the SMS message (" & j.ErrorMessage & ")","Error")
        Return
    End If
    j.Release
End Sub

Public Sub URLencode(InText As String) As String
    'works to url encode SMS params to twilio
    Dim C As Int 'As Integer
    Dim O As String
    Dim Z As Int 'As Long

    O = ""

    InText = InText.Replace(CRLF, Chr(10))

    For Z = 1 To InText.Length
        C = Asc(Mid(InText, Z, 1))

        If C = 13 Then C = 0
        If C = 94 Then C = 0

        Select Case C
            Case 10, 37, 38, 43, 94
                O = O & "%" & Pad(Bit.ToHexString(C), 2, "0")
            Case 32
                O = O & "+"
            Case Else
                If (C>32 And C<96) Or (C>96 And C<123) Then
                    O = O & Chr(C)
                End If
        End Select
    Next
    Return O
End Sub

Sub Pad(ItemToPad As String, ResultSize As Long, LeadPadding As String) As String
    'adds lead PADDING if ItemToPad is smaller then ResultSize
    Return Right(GenString(ResultSize, LeadPadding) & ItemToPad.Trim, ResultSize )
End Sub

Sub Right(Text As String, Length As Long) As String
    Dim R As String
    Try
        If Length > Text.Length Then Length = Text.Length
        R = Text.SubString(Text.Length - Length)
    Catch
        R = ""
    End Try
    Return R
End Sub

Sub GenString(NumChar As Long, Character As String) As String
    Dim Z As Long
    Dim R As String
    For Z = 1 To NumChar
        R = R & Character
    Next
    Return R
End Sub

Sub Mid(Text As String, Start As Int, Length As Int) As String
    Return Text.SubString2(Start-1,(Start + Length) -1)
End Sub
 
Last edited:

zabayin

Member
Licensed User
Longtime User
It never send sms. For e.g ...
To=+959778884343
Fail and it said wrong number sir.
 

JohnC

Expert
Licensed User
Longtime User
Log into your Twilio account and see if it gives more detail about the error (every use of the API is logged in your twilio account).

If not, then open a support ticket with twilio and have them research what the problem was.
 

zabayin

Member
Licensed User
Longtime User
Please kindly see my attachment sir.
Screenshot_20201221-112659~2.jpg

My account log is no different before and after sending sms. I think failed attempt is not counted by twilio. Not trial account and add credit 20 bulks.
I submit ticket and they never answer me. What a shame.
 
Last edited:

DonManfred

Expert
Licensed User
Longtime User
looks like the numer you are sending an SMS to is not valid. Does not look like an international formatted phone number!

I never saw any international number starting with 95977888


You attempted to initiate an outbound phone call, but the Called phone number you supplied was not a valid phone number or was incorrectly formatted. Twilio accepts phone numbers in E164 format: [+] [country code] [subscriber number including area code].


This error will also occur if you attempt to place a call or send a message from a Twilio phone number to itself (i.e. putting the same Twilio number in the To and From parameters).
 

zabayin

Member
Licensed User
Longtime User
This is Myanmar(Burma) Phone Number and actually exist sir :D (it's also my number) . The country code is +95 Myanmar(Burma) and 9 is the area code and I exactly obey the E164 rules. Please see the image sir. following is TO number.

1608578450493.png



and the following is FROM number. (Not Trial Account)

1608579259436.png


something is wrong. I think Is twilio api changed ? so that the code may be incompatible issues ?
the original post was no other comments. Just only me. oops !
 

JohnC

Expert
Licensed User
Longtime User
The error message indicates the number is bad, so I doubt the API changed because I would think it would give a different/more general error.

But, if you properly setup a support ticket on this issue with Twilio, Twilio should definitely get back to you soon - especially because you are a paying customer and this is not a free service.
 

JohnC

Expert
Licensed User
Longtime User
A couple of other things come to mind:

1) In post #2, it looks like you are putting a "+" sign at the start of the number, but the posted error message looks like the "+" is missing.
2) It looks like the "From" phone number is a US based number and you are trying to send to another country (Burma) - as a test, try buying a Burma number (maybe Burma country code is not even supported by twilio at this time?) from twilio and then try to send from the twilio Burma number to the desired Burma number?
 
Last edited:

zabayin

Member
Licensed User
Longtime User
I Found Solution ! For those who faced with the terrible issue. I was modified JohnC original code at this line

[CODE lang="b4x" title="Original Code without %2B in "To" Keyword"]P = "From=%2B" & TNumber & "&To=" & NumbertoSendto & "&Body=" & URLencode(MessageToSend)[/CODE]

INTO ...

[CODE lang="b4x" title="Modified "To" Keyword with %2B"]P = "From=%2B" & TNumber & "&To=%2B" & NumbertoSendto & "&Body=" & URLencode(MessageToSend)[/CODE]

and Viola ! Everything is Now OK. I don't know what the "%2B" is that :) but my seventh sense make the day. LOL ! Thank you for this Great Code Sir. Really Appreciated.
 

zabayin

Member
Licensed User
Longtime User
It depends on how the number is stored in your Database.
%2B is the + sign i guess. If you do not have this + in your database then you need to add it like this.
The number is not came from database mr.don. I just test with provided code with my number.
 

JohnC

Expert
Licensed User
Longtime User
The error was correct because the "to" number that you provided (which started with 95977888), did not include a properly formatted country code because it was missing the required leading "+".

The plus sign "+" is needed when using a country code, that's why my example code adds the "+" sign (via the %2B") to the "From" number.
 

JohnC

Expert
Licensed User
Longtime User
Also, I just noticed that your example in post #2 did properly include the leading "+", so that would have worked.

I guess you forgot to include the "+" when you actually ran your code and called my routine.
 

zabayin

Member
Licensed User
Longtime User
I Not Forgot + sign sir. The only difference situation of Fail or Success is ....

B4X:
P = "From=%2B" & TNumber & "&To=%2B" & NumbertoSendto & "&Body=" & URLencode(MessageToSend) '------> Success !

B4X:
P = "From=%2B" & TNumber & "&To=" & NumbertoSendto & "&Body=" & URLencode(MessageToSend) '------ > Failed !


My Number is not Changed. I Simply use .. your code sir.

B4X:
SendTwilioSMS("+95997288xxxx","125358 is your Code !")
 

JohnC

Expert
Licensed User
Longtime User
It looks like "+" characters in the phone number need to be encoded to "%2B" for the API to work.
 

zabayin

Member
Licensed User
Longtime User
It looks like "+" characters in the phone number need to be encoded to "%2B" for the API to work.
Exactly sir. I think the code will also work in B4i. I'll try later and post back it's really cross-platform supported or not.
 

JohnC

Expert
Licensed User
Longtime User
Exactly sir. I think the code will also work in B4i. I'll try later and post back it's really cross-platform supported or not.
This is a REST API, so it should work "from" any platform.
 

JohnC

Expert
Licensed User
Longtime User
I updated the code and remarks in the OP to indicate that both the From and To need to include the country code, but not the leading "+" of it.
 
Last edited:

paris7162

Member
Licensed User
Longtime User
Can you send MMS with this? Not the Url to the media but send the actual media from the gallery of phots on the device?
 

JohnC

Expert
Licensed User
Longtime User
Can you send MMS with this? Not the Url to the media but send the actual media from the gallery of phots on the device?
Yes, you can send a photo and the recipient will receive the actual photo (not a link).

However, the API requires that the media (to be sent) is located at an internet address. Since phones do not have a fixed IP, you would need to first copy the media to a web server, then call the API with that address.
 
Last edited:
Top