How to Send SMS from API or Backend 📲

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 sent programmatically.

  1. Promotional SMS
  2. 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

sms opt-in proof example
Opt-in proof

You’ll receive a sample format for letter of consent in which you can fill your name, your business name, sign it and send it.

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

SMS template example
SMS template example

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.

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 with 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 URLAPI key and Sender ID need not be passed in every request manually.

I’ve created a file named smsClient.js where multiple functions are defined for different SMS. Now, All we need to do is import the smsClient and call appropriate functions wherever required.

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

<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.IO" %>
 
<script runat="server" language="VB">
  
    Sub Page_Load(sender As Object, e As EventArgs)
        
        Dim apikey As String = "YourapiKey"
 
        Dim SenderName As String = "YOUR SENDER ID"
        Dim Number As String = "918123456789"
        Dim Message As String = "This is an API message"
        Dim URL As String = "https://api.textlocal.in/send/?"
        Dim PostData As String = "apikey=" & apikey & "&sender=" & SenderName & "&numbers=" & Number & "&message=" & Message
        Dim req As HttpWebRequest = WebRequest.Create(URL)
        req.Method = "POST"
        Dim encoding As New ASCIIEncoding()
        Dim byte1 As Byte() = encoding.GetBytes(PostData)
        req.ContentType = "application/x-www-form-urlencoded"
        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("SOMETHING WENT AWRY!
Status: " & wex.Status & "Message: " & wex.Message & "")
        End Try
    End Sub
 
</script>

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😂

Author: Ranjith kumar

A CA student by education, self taught coder by passion, loves to explore new technologies and believes in learn by doing.

3 Thoughts

  1. 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

Leave a Reply

Your email address will not be published. Required fields are marked *