How to Send SMS Messages in Node.js via SMPP Gateway

SMS (Short Message Service) is a ubiquitous communication channel that allows sending text messages to mobile phones. It is widely used for notifications, alerts, marketing campaigns and two-factor authentication.

While there are many ways to send SMS messages from a software application, SMPP (Short Message Peer-to-Peer) is the most common protocol used by telecoms to exchange SMS messages between systems. It is an open, industry-standard protocol designed for high throughput and reliability.

In this tutorial, we will learn how to send SMS messages from a Node.js application using SMPP protocol. We will use the node-smpp library to communicate with a SMPP gateway and send messages to mobile phone numbers. Let‘s get started!

Prerequisites

Before we begin, make sure you have the following:

  • Node.js installed on your system (version 10 or higher)
  • A SMPP account with a service provider (you‘ll need the host, port, username and password)
  • A mobile phone to test the SMS

Setting up the Project

First, let‘s create a new directory for our project and initialize a new Node.js application:


mkdir smpp-demo
cd smpp-demo
npm init -y

Next, install the node-smpp library using npm:


npm install smpp --save

The node-smpp library provides a simple interface to connect to a SMPP server and send/receive messages. It handles the low-level details of the SMPP protocol and provides a callback-based API.

Connecting to the SMPP Server

To send SMS messages via SMPP, we first need to establish a session with the SMPP gateway. Here‘s how to do it:


const smpp = require(‘smpp‘);

const session = new smpp.Session({ host: ‘smpp.provider.com‘, port: 2775, });

session.on(‘connect‘, () => { session.bind_transceiver({ system_id: ‘YOUR_USERNAME‘, password: ‘YOUR_PASSWORD‘, }, (pdu) => { if (pdu.command_status === 0) { console.log(‘Successfully connected to SMPP server‘); } else { console.error(‘Error connecting to SMPP server:‘, pdu.command_status); } }); });

session.on(‘error‘, (error) => { console.error(‘SMPP error:‘, error); });

Let‘s break this down:

  1. We require the smpp module and create a new Session instance with the host and port of the SMPP gateway.

  2. We listen for the connect event, which is fired when the session is established with the server.

  3. In the connect event handler, we call bind_transceiver to authenticate with the server using our username and password.

  4. The bind_transceiver function takes a callback that receives a PDU (Protocol Data Unit) object. We check the command_status field to determine if the bind was successful (0 means success).

  5. We also listen for the error event to handle any errors that may occur during the session.

Make sure to replace YOUR_USERNAME and YOUR_PASSWORD with your actual SMPP credentials.

Sending SMS Messages

Now that we have a session established with the SMPP server, we can start sending SMS messages. Here‘s an example function to send an SMS:


function sendSMS(from, to, text, callback) {
  from = `+${from}`;
  to = `+${to}`;

session.submit_sm({ source_addr: from, destination_addr: to, short_message: text, }, (pdu) => { if (pdu.command_status === 0) { console.log(Message sent successfully to ${to}); callback(null, pdu.message_id); } else { console.error(Error sending message to ${to}:, pdu.command_status); callback(pdu.command_status, null); } }); }

The sendSMS function takes four parameters:

  • from: The sender‘s phone number (your SMPP account phone number)
  • to: The recipient‘s phone number
  • text: The message content (up to 160 characters for a single SMS)
  • callback: A callback function to handle the response

Inside the function, we do the following:

  1. Prepend a ‘+‘ to the from and to phone numbers (this is required by SMPP).

  2. Call submit_sm on the session to send the SMS. We pass an object with the source address, destination address, and message text.

  3. In the callback, we check the command_status field of the response PDU. A status of 0 means the message was successfully sent.

  4. We log a success message and invoke the callback with null for error and the message_id. In case of an error, we log the status code and invoke the callback with the status code as error.

To test this function, you can add the following code to your script:


const from = ‘1234567890‘;
const to = ‘9876543210‘;
const text = ‘Hello, world!‘;

sendSMS(from, to, text, (error, messageId) => { if (error) { console.error(‘Error sending SMS:‘, error); } else { console.log(SMS sent successfully. Message ID: ${messageId}); } });

Replace the from and to numbers with your own SMPP account phone number and the recipient‘s number.

Run the script and you should see a success message logged to the console and the SMS delivered to the recipient‘s phone. Congratulations, you‘ve just sent an SMS using SMPP in Node.js!

Handling Delivery Reports

In addition to sending messages, the SMPP protocol also allows receiving delivery reports from the carrier. A delivery report indicates whether a message was successfully delivered to the recipient‘s handset or if it failed.

To handle delivery reports, we need to listen for the deliver_sm event on the SMPP session. Here‘s an example:


session.on(‘deliver_sm‘, (pdu) => {
  const message = pdu.short_message.message;

if (pdu.esm_class === 4) { // This is a delivery report const report = pdu.short_message.message.split(‘ ‘)[0];

if (report === ‘id:‘) {
  const messageId = message.split(‘ ‘)[1];
  const state = message.split(‘ ‘)[2];
  const status = message.split(‘ ‘)[7];

  console.log(`Delivery report for message ${messageId}: ${state} (${status})`);
}

} else {
// This is a regular SMS
const from = pdu.source_addr;
const to = pdu.destination_addr;

console.log(`Received SMS from ${from} to ${to}: ${message}`);    

}
});

When a deliver_sm event is received, we extract the short_message field from the PDU, which contains the actual message content.

We then check the esm_class field to determine whether this is a delivery report (indicated by a value of 4) or a regular incoming SMS.

For delivery reports, the message text has a specific format that includes the original message ID, delivery state, and status code. We parse these values and log a message indicating the delivery status of the SMS.

For regular incoming SMS messages, we simply extract the source and destination addresses and log the message content.

Note that in order to receive delivery reports, you may need to configure your SMPP account to request delivery reports for outgoing messages. Consult your SMPP provider‘s documentation for instructions on how to do this.

Best Practices and Optimizations

When building an SMPP application that sends a high volume of messages, there are a few best practices and optimizations to keep in mind:

  1. Connection Pooling: Establishing a new SMPP session for each message can be inefficient. Instead, create a pool of reusable sessions and allocate them to sending tasks as needed. The generic-pool library is a good choice for this.

  2. Throughput Optimization: To achieve high throughput, you can send messages concurrently by submitting multiple submit_sm PDUs without waiting for the response. However, be aware of any rate limits imposed by your SMPP provider.

  3. Error Handling: Proper error handling is crucial to ensure your application can recover from transient failures. Implement retry mechanisms with exponential backoff and set reasonable timeouts for unresponsive connections.

  4. Logging and Monitoring: Use a logging library like winston or bunyan to log important events and errors. Set up monitoring and alerting for key metrics like message throughput, delivery success rate, and latency.

  5. Security: Protect your SMPP credentials and never hardcode them in your source code. Use environment variables or a secure secrets management system. Also, consider using SSL/TLS to encrypt the SMPP traffic if supported by your provider.

Advanced Topics

While sending and receiving SMS messages covers the basic functionality of SMPP, there are a few advanced topics worth mentioning:

  • Long SMS: For messages longer than 160 characters, you need to split them into multiple parts and send them as concatenated SMS. The node-smpp library supports this through the esm_class and udh options.

  • Flash Messages: Flash SMS messages are displayed immediately on the recipient‘s screen without being stored in the inbox. To send a flash message, set the data_coding option to 240.

  • Encoding: To send non-ASCII characters (e.g., Unicode), you need to specify the appropriate encoding scheme through the data_coding option. Common values are 8 (UCS2) and 0 (GSM 7-bit).

  • Status Reports: In addition to delivery reports, you can request status reports for each message by setting the registered_delivery option to 1. Status reports provide more detailed information about the message lifecycle.

Conclusion

In this tutorial, we learned how to send and receive SMS messages using the SMPP protocol in Node.js. We used the node-smpp library to establish a session with an SMPP gateway, send messages with submit_sm, and handle delivery reports with the deliver_sm event.

We also discussed some best practices and optimizations for building high-performance SMPP applications, such as connection pooling, error handling, and logging.

SMPP is a powerful protocol for SMS messaging and is widely used by carriers and service providers around the world. With the knowledge gained from this tutorial, you should be able to build your own SMS applications in Node.js with confidence.

So go ahead and experiment with the code samples, integrate SMS capabilities into your applications, and feel free to reach out if you have any questions or feedback. Happy coding!

Similar Posts