How to Send SMS through the SMPP API using Python

The Short Message Peer-to-Peer (SMPP) API is a widely adopted protocol for exchanging SMS messages between SMS entities like ESMEs (External Short Message Entities) and SMSCs (Short Message Service Centers). For users of the Ozeki SMS Gateway platform, understanding SMPP protocol-level i nteractions is critical for optimizing performance, debugging, and custom integrations. This guide explains the SMPP PDUs (Protocol Data Units) required to establish, maintain, and use an SMPP API connection to send SMS messages, with practical Python examples.

Figure 1 - Send SMS from Python using the SMPP API

How to Send SMS through the SMPP API using Python (Quick Steps)

  1. Check the SMPP credentials
  2. Write and run the Python script
  3. Verify the result

How to Send SMS through the SMPP API using Python (Video tutorial)

In this video, you will learn how to send SMS messages using Python through the SMPP API with Ozeki SMS Gateway. The tutorial shows how to set up an SMPP user, connect using the smpplib library, and send an SMS with a few lines of code. You’ll also see how to keep the connection alive and handle delivery reports. By the end, you’ll have a working Python script ready to send SMS messages via SMPP.

Step 1 - Select SMPP User

In the Ozeki SMS Gateway interface, go to the "Users and applications" section and select the previously created SMPP user. This user is required for establishing the SMPP connection from Python.

Select SMPP User
Figure 2 - Select SMPP User

Step 2 - Connection details

After selecting the SMPP user, go to the "Help" tab and you will see connection details such as IP address, port number, username, and password. These values will be used in your Python code to connect to the SMS Gateway.

Connection details
Figure 3 - Connection details

Step 3 - Paste the Python code

Open your IDE or Python editor and paste the "Complete Python SMPP API Client Example for Sending SMS" SMPP connection code from below using the smpplib library. This code initiates the connection and prepares the environment for sending SMS.

Paste the Python code
Figure 4 - Paste the Python code

Step 4 - Replace data

Update the placeholder values in the code with your actual SMPP credentials (host, port, username, password) and the phone numbers you want to use for sending messages.

Replace data
Figure 5 - Replace data

Step 5 - Successful

Run the script. If everything is set up correctly, in the Ozeki SMS Gateway interface, the created smpp_user will show in the log that it was successful. Confirming the connection is live and ready to send messages.

Successful login
Figure 6 - Successful login

How to Establish an SMPP API Connection in Python for SMS Messaging

To send SMS via SMPP API, you must first setup an SMPP user, and then bind your client to the Ozeki SMS Gateway's SMPP server. Here's how to do it in Python using the smpplib library:

import smpplib

# Connection parameters
HOST = 'your.ozeki.server'
PORT = 2775
SYSTEM_ID = 'your_username'
PASSWORD = 'your_password'

# Create client
client = smpplib.client.Client(HOST, PORT)

# Bind as transmitter
client.connect()
client.bind_transmitter(
    system_id=SYSTEM_ID,
    password=PASSWORD,
)

print("Successfully bound to the SMPP server")

Key PDUs for Connection Setup

PDU Python Method Purpose
bind_transmitter client.bind_transmitter() Initiates a connection for sending SMS
bind_receiver client.bind_receiver() Sets up a connection for receiving SMS
bind_transceiver client.bind_transceiver() Enables bidirectional messaging

Maintaining a Stable SMPP API Connection in Python for SMS Sending

SMPP connections require periodic keep-alive signals to prevent timeout. Here's how to implement it in Python:

import time
import threading

def send_enquire_link():
    while True:
        try:
            client.enquire_link()
            print("Sent enquire_link PDU")
        except Exception as e:
            print(f"Error sending enquire_link: {e}")
        time.sleep(30)  # Send every 30 seconds

# Start keep-alive thread
keepalive_thread = threading.Thread(target=send_enquire_link)
keepalive_thread.daemon = True
keepalive_thread.start()

Sending SMS with Python through the SMPP API

Here's a complete example of sending an SMS and handling the response:

def send_sms(source_addr, destination_addr, message):
    try:
        # Send submit_sm PDU
        pdu = client.send_message(
            source_addr_ton=smpplib.consts.SMPP_TON_INTL,
            source_addr_npi=smpplib.consts.SMPP_NPI_ISDN,
            source_addr=source_addr,
            dest_addr_ton=smpplib.consts.SMPP_TON_INTL,
            dest_addr_npi=smpplib.consts.SMPP_NPI_ISDN,
            destination_addr=destination_addr,
            short_message=message,
            data_coding=0x00,  # GSM 7-bit encoding
        )
        
        print(f"Message submitted, message_id: {pdu.message_id}")
        
    except smpplib.exceptions.PDUError as e:
        print(f"PDU error: {e}")
    except Exception as e:
        print(f"Error sending SMS: {e}")

# Example usage
send_sms(
    source_addr="12345",
    destination_addr="+1234567890",
    message="Hello from Python SMPP client!"
)

Handling Delivery Reports

To receive delivery reports in Python:

def handle_delivery_report(pdu):
    print(f"Received delivery report for message {pdu.receipted_message_id}")
    print(f"Status: {pdu.message_state}")

# Set up delivery report handler
client.set_message_received_handler(lambda pdu: handle_delivery_report(pdu))

Complete Python SMPP API Client Example for Sending SMS

Here's a complete working example:

import smpplib
import threading
import time

class SMPPClient:
    def __init__(self, host, port, system_id, password):
        self.client = smpplib.client.Client(host, port)
        self.client.set_message_received_handler(self.handle_message)
        
        # Bind to server
        self.client.connect()
        self.client.bind_transceiver(
            system_id=system_id,
            password=password,
        )
        
        # Start keep-alive
        self.start_keepalive()
    
    def start_keepalive(self):
        def _keepalive():
            while True:
                try:
                    self.client.enquire_link()
                except Exception:
                    try:
                        self.client.connect()
                        self.client.bind_transceiver(
                            system_id=SYSTEM_ID,
                            password=PASSWORD,
                        )
                    except Exception as e:
                        print(f"Reconnection failed: {e}")
                time.sleep(30)
        
        thread = threading.Thread(target=_keepalive)
        thread.daemon = True
        thread.start()
    
    def send_sms(self, from_addr, to_addr, message):
        try:
            return self.client.send_message(
                source_addr=from_addr,
                destination_addr=to_addr,
                short_message=message,
            )
        except Exception as e:
            print(f"Send failed: {e}")
            return None
    
    def handle_message(self, pdu):
        if pdu.command == "deliver_sm":
            print(f"Delivery report: {pdu.receipted_message_id} - {pdu.message_state}")
        else:
            print(f"Received message: {pdu.short_message}")

# Usage
if __name__ == "__main__":
    client = SMPPClient(
        host="your.ozeki.server",
        port=2775,
        system_id="your_username",
        password="your_password"
    )
    
    # Send a message
    client.send_sms(
        from_addr="12345",
        to_addr="+1234567890",
        message="Hello from complete Python SMPP client!"
    )
    
    # Keep running
    while True:
        time.sleep(1)

Conclusion

This guide has shown you how to work with the SMPP API at the protocol level using Python. By implementing these examples with Ozeki SMS Gateway, you can build robust SMS applications with features like connection management, message sending, and delivery report handling. The smpplib library provides a convenient way to work with SMPP PDUs while handling the low-level protocol details for you.

Remember to handle exceptions properly in production code and implement reconnection logic for maximum reliability. The complete example provided includes basic reconnection handling and keep-alive functionality.

More information