Sending SMS is one of the essential features for any app’s backend. I’ve recently started working on an app and I needed an SMS service to send transactional SMS
After some research, I found Textlocal to be a viable option with decent pricing, automated campaigns, automated reports, and good support. Their approval process was pretty fast as well.
SMS approval process for developers
Most beginner developers might not know the process of SMS approval. It is not pretty straight-forward. There are some rules for what SMS can be sent, what ID you’ll be assigned, and at what time the SMS can be sent. Let’s check it out
There are different rules in different countries with regard to SMS depending on the telecom authority of that country. I’m explaining these from India’s perspective.
Types of SMS
There are two types of SMS which can be
- Promotional SMS
- Transactional SMS
Promotional SMS
Promotional SMS is used to send promotions, offers, discounts etc. to the users. This SMS is not really important for users.
There’s no approval needed for promotional SMS. You can simply register with any SMS provider and start sending single or bulk SMS from the service provider’s web dashboard.
This is the type of SMS that could lead to spam so there are some rules with promotional SMS
- Promotional SMS can only be sent between 9 AM and 9 PM
- Promotional SMS is not sent to DND (Do not disturb) numbers
- Promotional SMS is sent from a random ID which is available from the service provider at the time of sending SMS
Transactional SMS
Transactional SMS is used to send welcome SMS, verification codes, OTPs, Order status SMS etc. Transactional SMS doesn’t have any limit on the timings and the SMS will also be sent to DND numbers.
Transactional SMS has an approval process. You need to send a few documents to the service provider. Documents are as follows :
1. Opt-in permission in the privacy policy
2. Letter of consent
Here’s an example of opt-in proof
You’ll receive a sample format for
You should also mention the 6 letter ID that you would like to use as sender ID. It should be unique.
The service provider will verify your documents and approve your account for transactional SMS. This is the initial approval process.
Transactional SMS templates
Only pre-approved SMS templates can be sent as transactional SMS. This limit is to make sure that users won’t use the transactional SMS to send promotional SMS content.
Here’s an example of SMS template for sending verification code or OTP
Once the template is approved, You can start sending SMS from the service provider’s dashboard or using their API.
Many Service providers have client libraries and SDKs to make it easier for the developers to send SMS programmatically.
Send SMS using Node.js
I’m using Text Local as the SMS service provider and we have an Express Node.js backend. Let me show you how we send SMS from API in our Express app. Check out the code below.
//This code was posted for an article at https://codingislove.com/send-sms-developers/ | |
const axios = require("axios"); | |
const tlClient = axios.create({ | |
baseURL: "https://api.textlocal.in/", | |
params: { | |
apiKey: "YOUR API KEY", //Text local api key | |
sender: "6 CHARACTER SENDER ID" | |
} | |
}); | |
const smsClient = { | |
sendPartnerWelcomeMessage: user => { | |
if (user && user.phone && user.name) { | |
const params = new URLSearchParams(); | |
params.append("numbers", [parseInt("91" + user.phone)]); | |
params.append( | |
"message", | |
`Hi ${user.name}, | |
Welcome to iWheels, Download our app to get bookings from our customers with better pricing. | |
https://iwheels.co` | |
); | |
tlClient.post("/send", params); | |
} | |
}, | |
sendVerificationMessage: user => { | |
if (user && user.phone) { | |
const params = new URLSearchParams(); | |
params.append("numbers", [parseInt("91" + user.phone)]); | |
params.append( | |
"message", | |
`Your iWheels verification code is ${user.verifyCode}` | |
); | |
tlClient.post("/send", params); | |
} | |
} | |
}; | |
module.exports = smsClient; | |
// Now import the client in any other file or wherever required and run these functions | |
// const smsClient = require("./smsClient"); | |
// smsClient.sendVerificationMessage(user) |
SMS Code explanation
The service provider that I’m using has a REST API. All we need to do is send a POST request to the API API key
sender ID
phone number
and the message body
Read Text Local documentation here
I’m using Axios as the Rest client. We don’t need any external client in this case but Axios helps us in creating a client instance with default params so that the API URL
, API key
Sender ID
I’ve created a file named smsClient.js
where multiple functions are defined for different SMS. Now, All we need to do is import smsClient
Send SMS PHP example
<?php $apiKey = urlencode('Your apiKey'); // Message details $numbers = array(918123456789, 918987654321); $sender = urlencode('YOUR SENDER ID'); $message = rawurlencode('This is your message'); $numbers = implode(',', $numbers); // Prepare data for POST request $data = array('apikey' => $apiKey, 'numbers' => $numbers, "sender" => $sender, "message" => $message); // Send the POST request with cURL $ch = curl_init('https://api.textlocal.in/send/'); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); // Process your response here echo $response; ?>
Send SMS Python example
#!/usr/bin/env python import urllib.request import urllib.parse def sendSMS(apikey, numbers, sender, message): data = urllib.parse.urlencode({'apikey': apikey, 'numbers': numbers, 'message' : message, 'sender': sender}) data = data.encode('utf-8') request = urllib.request.Request("https://api.textlocal.in/send/?") f = urllib.request.urlopen(request, data) fr = f.read() return(fr) resp = sendSMS('apikey', '918123456789', 'Jims Autos', 'This is your message') print (resp)
Send SMS Ruby example
require "rubygems" require "net/https" require "uri" require "json" requested_url = 'https://api.textlocal.in/send/?' uri = URI.parse(requested_url) http = Net::HTTP.start(uri.host, uri.port) request = Net::HTTP::Get.new(uri.request_uri) res = Net::HTTP.post_form(uri, 'apikey' => 'yourApikey', 'message' => 'This is your message', 'sender' => 'Ben', 'numbers' => '918123456789') response = JSON.parse(res.body) puts (response)
Send SMS Java example
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; public class sendSMS { public String sendSms() { try { // Construct data String apiKey = "apikey=" + "yourapiKey"; String message = "&message=" + "This is your message"; String sender = "&sender=" + "TXTLCL"; String numbers = "&numbers=" + "918123456789"; // Send data HttpURLConnection conn = (HttpURLConnection) new URL("https://api.textlocal.in/send/?").openConnection(); String data = apiKey + numbers + message + sender; conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Length", Integer.toString(data.length())); conn.getOutputStream().write(data.getBytes("UTF-8")); final BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); final StringBuffer stringBuffer = new StringBuffer(); String line; while ((line = rd.readLine()) != null) { stringBuffer.append(line); } rd.close(); return stringBuffer.toString(); } catch (Exception e) { System.out.println("Error SMS "+e); return "Error "+e; } } }
Send SMS VBA example
Public Sub Send() Dim username As String Dim password As String Dim result As String Dim myURL As String Dim Sender As String Dim numbers As String Dim Message As String Dim postData As String Dim winHttpReq As Object apikey = "yourAPIkey" Sender = "YOUR SENDER ID" numbers = "918123456789" Message = "This is your message" Set winHttpReq = CreateObject("WinHttp.WinHttpRequest.5.1") myURL = "https://api.textlocal.in/send/?" postData = "apikey=" + apikey + "&message=" + Message + "&numbers=" + numbers + "&sender=" + Sender winHttpReq.Open "POST", myURL, False winHttpReq.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded" winHttpReq.Send (postData) SendSMS = winHttpReq.responseText End Sub
Send SMS VB.NET example
Imports System.Web Imports System.IO Imports System.Net Imports System.Text Imports System.Resources Public Class sendSMS Public Function sendSMS() Dim apikey = "yourAPIkey" Dim message = "This is your message" Dim numbers = "918123456789" Dim strPost As String Dim sender = "YOUR SENDER ID" Dim url As String = "https://api.textlocal.in/send/?" Dim strPost As String strPost = url + "apikey=" + apikey _ + "&numbers=" + numbers _ + "&message=" + WebUtility.UrlEncode(message) _ + "&sender=" + sender Dim request As WebRequest = WebRequest.Create(strPost) request.Method = "POST" Dim byteArray As Byte() = Encoding.UTF8.GetBytes(strPost) request.ContentType = "application/x-www-form-urlencoded" request.ContentLength = byteArray.Length Dim dataStream As Stream = request.GetRequestStream() dataStream.Write(byteArray, 0, byteArray.Length) dataStream.Close() Dim response As WebResponse = request.GetResponse() dataStream = response.GetResponseStream() Dim reader As New StreamReader(dataStream) Dim responseFromServer As String = reader.ReadToEnd() Console.WriteLine(responseFromServer) Console.ReadLine() reader.Close() dataStream.Close() response.Close() If responseFromServer.Length > 0 Then Return responseFromServer Else Return CType(response, HttpWebResponse).StatusDescription End If End Function End Class
Send SMS C# example
using System; using System.Collections.Generic; using System.Net; using System.Collections.Specialized; namespace sendSMS { class sendSMS { public string sendSMS() { String message = HttpUtility.UrlEncode("This is your message"); using (var wb = new WebClient()) { byte[] response = wb.UploadValues("https://api.textlocal.in/send/", new NameValueCollection() { {"apikey" , "yourapiKey"}, {"numbers" , "918123456789"}, {"message" , message}, {"sender" , "YOUR SENDER ID"} }); string result = System.Text.Encoding.UTF8.GetString(response); return result; } } } }
Send SMS ASP.NET example
&amp;lt;%@ Import Namespace=&amp;quot;System.Net&amp;quot; %&amp;gt; &amp;lt;%@ Import Namespace=&amp;quot;System.IO&amp;quot; %&amp;gt; &amp;lt;script runat=&amp;quot;server&amp;quot; language=&amp;quot;VB&amp;quot;&amp;gt; Sub Page_Load(sender As Object, e As EventArgs) Dim apikey As String = &amp;quot;YourapiKey&amp;quot; Dim SenderName As String = &amp;quot;YOUR SENDER ID&amp;quot; Dim Number As String = &amp;quot;918123456789&amp;quot; Dim Message As String = &amp;quot;This is an API message&amp;quot; Dim URL As String = &amp;quot;https://api.textlocal.in/send/?&amp;quot; Dim PostData As String = &amp;quot;apikey=&amp;quot; &amp;amp; apikey &amp;amp; &amp;quot;&amp;amp;sender=&amp;quot; &amp;amp; SenderName &amp;amp; &amp;quot;&amp;amp;numbers=&amp;quot; &amp;amp; Number &amp;amp; &amp;quot;&amp;amp;message=&amp;quot; &amp;amp; Message Dim req As HttpWebRequest = WebRequest.Create(URL) req.Method = &amp;quot;POST&amp;quot; Dim encoding As New ASCIIEncoding() Dim byte1 As Byte() = encoding.GetBytes(PostData) req.ContentType = &amp;quot;application/x-www-form-urlencoded&amp;quot; req.ContentLength = byte1.Length Dim newStream As Stream = req.GetRequestStream() newStream.Write(byte1, 0, byte1.Length) Try Dim resp As HttpWebResponse = req.GetResponse() Dim sr As New StreamReader(resp.GetResponseStream()) Dim results As String = sr.ReadToEnd() sr.Close() html.Text = results Catch wex As WebException Response.Write(&amp;quot;SOMETHING WENT AWRY! Status: &amp;quot; &amp;amp; wex.Status &amp;amp; &amp;quot;Message: &amp;quot; &amp;amp; wex.Message &amp;amp; &amp;quot;&amp;quot;) End Try End Sub &amp;lt;/script&amp;gt;
Wrapping up
It doesn’t matter which language you are using, It is ultimately a simple POST request with the data as params. Almost all SMS service providers have a REST API. Read the documentation once and implement it!
Happy texting 😍📲
Recent articles :
Speech recognition and synthesis with simple JavaScript
Sarcastic web services and websites that actually exist😂
- Flutter lookup failed in @fields error (solved) - July 14, 2023
- Free open source alternative to Notion along with AI - July 13, 2023
- Threads API for developers for programmatic access - July 12, 2023
i dont get javascript using api send sms
Hey Shahid, Node.js is nothing but javascript
Hi Ranjit, your blog article for sending SMS came up on my newsfeed and I wanted to reach out.
First off, I thought codingislove.com is a pretty cool idea. I also wanted to share that you can access Telesign or Nexmo APIs, or any of our 8000 other APIs via Rakuten RapidAPI (https://re.tc/in74g3xc)- we’re the world’s largest API Marketplace with 500k developers. We’d love to get on a call and do a demo for you.
We’d be happy to offer you a free coupon credit. You can claim it here https://re.tc/sggdqmbv
very interesting and inspiring article.
coding is my passion.
very interesting and inspiring article.