ES

Blog de LabsMobile noticias y novedades

How to Send SMS Messages with Python Step by Step [Practical Guide]

Nowadays, where communication is instant, sending SMS messages through Python has become a very effective option to interact with clients and users. SMS arrive within seconds and are usually read immediately, making them a very powerful communication channel.

In this article, we show how to carry out the SMS integration with Python. A step-by-step guide, with examples and everything needed to start sending your first SMS messages with Python from your application.

13 minutes of reading
Publication: 10.06.2025
Categories: API SMS

Regístrate y prueba enviar SMS con LabsMobile

¡Empieza aquí y ahora!
All included from
per SMS to United States

Introduction to the manual on how to send SMS with Python

Communication via SMS is one of the most effective methods to ensure that an important message reaches the user directly. By incorporating SMS sending into Python applications, it is possible to design automated flows for system alerts, appointment reminders, or transaction notifications, with full traceability and speed.

The LabsMobile API offers a secure environment based on JSON requests over HTTPS and token-based authentication, making integration easy for projects of any size. This introduction describes the main usage scenarios and the essential requirements to start implementing this functionality easily.

Why use Python to send SMS?

Python is a very popular programming language in web and application development. Its clear syntax and rich library ecosystem make it easy to integrate external services, including SMS messaging. Thanks to third-party libraries and frameworks, creating a script to send SMS is relatively simple. You only need the Python language, the provider’s API credentials, and a short code snippet for the API.

  • Development speed: short scripts allow SMS sending to be set up in no time.
  • Flexibility: simple integration in web applications, REST APIs, or batch processes.
  • Portability: code compatible with multiple operating systems without modifications.
  • Readable syntax: makes maintenance and team collaboration easier.
  • Prerequisites

    To send SMS with Python using the LabsMobile API, the following is required:

  • Active LabsMobile account (username and API token): in the LabsMobile platform and obtain your credentials (username and API token).
  • Python 3 installed on the system.
  • requests library installed (pip install requests).
  • Internet connection via HTTPS to ensure secure transmission.
  • Steps to send SMS with Python

    1. Prepare credentials: generate the user:token pair and encode it in Base64 for the Authorization header.
    2. Define the API URL: use https://api.labsmobile.com/json/send with a POST request.
    3. Create the JSON payload: include sender (tpoa), recipients, and message text.
    4. Send the HTTP request: use requests.post with headers Content-Type: application/json and Authorization: Basic <credentials>.
    5. Process the response: validate the code field in the JSON to confirm delivery.

    Example JSON payload

    {

    "message": "Your verification code is 1234",

    "tpoa": "MySender",

    "recipient": [

    { "msisdn": "34123456789" }

    ]

    }

    Integration examples in an application

    Insert a new user in an SQLite database and send a welcome message:

    import sqlite3, requests, base64, json

    # --- 1. Register in the database ---

    conn = sqlite3.connect('users.db')

    cursor = conn.cursor()

    cursor.execute("INSERT INTO users (name, phone) VALUES (?, ?)", ('Lucía', '34123456789'))

    conn.commit()

    # --- 2. Prepare SMS ---

    user_token = 'LabsmobileUser:APIToken'

    credentials = base64.b64encode(user_token.encode()).decode()

    url = 'https://api.labsmobile.com/json/send'

    payload = json.dumps({

    'message': 'Welcome Lucía, thank you for joining our platform!',

    'tpoa': 'MyApp',

    'recipient': [{'msisdn': '34123456789'}]

    })

    headers = {

    'Content-Type': 'application/json',

    'Authorization': f'Basic {credentials}'

    }

    # --- 3. Send request and process response ---

    response = requests.post(url, headers=headers, data=payload)

    print('SMS Response:', response.json())

    Save order in the database and notify the user:

    import sqlite3, requests, base64, json

    # --- 1. Save order in database ---

    conn = sqlite3.connect('orders.db')

    cursor = conn.cursor()

    cursor.execute("INSERT INTO orders (user, product, phone) VALUES (?, ?, ?)",

    ('Carlos', 'Sports Shoes', '34111222333'))

    conn.commit()

    # --- 2. Prepare SMS ---

    user_token = 'LabsmobileUser:APIToken'

    credentials = base64.b64encode(user_token.encode()).decode()

    url = 'https://api.labsmobile.com/json/send'

    payload = json.dumps({

    'message': 'Hello Carlos, your order of "Sports Shoes" has been confirmed and is being prepared.',

    'tpoa': 'MyStore',

    'recipient': [{'msisdn': '34111222333'}]

    })

    headers = {

    'Content-Type': 'application/json',

    'Authorization': f'Basic {credentials}'

    }

    # --- 3. Send SMS ---

    response = requests.post(url, headers=headers, data=payload)

    print('Order SMS Response:', response.json())

    Send a bank transaction alert:

    import requests, base64, json

    # --- 1. Transaction data ---

    amount = 1250.00

    card = "****6789"

    phone = "34122334455"

    # --- 2. Prepare SMS ---

    user_token = 'LabsmobileUser:APIToken'

    credentials = base64.b64encode(user_token.encode()).decode()

    url = 'https://api.labsmobile.com/json/send'

    payload = json.dumps({

    'message': f'Alert: a charge of ${amount:.2f} was made on your card {card}.',

    'tpoa': 'SecureBank',

    'recipient': [{'msisdn': phone}]

    })

    headers = {

    'Content-Type': 'application/json',

    'Authorization': f'Basic {credentials}'

    }

    # --- 3. Send SMS ---

    response = requests.post(url, headers=headers, data=payload)

    print('Bank SMS Response:', response.json())

    Security and best practices

    Security is essential:

  • Always use HTTPS to encrypt requests.
  • Store credentials in environment variables or configuration files outside the code.
  • Activate IP filtering, adding the IP addresses from which API requests will be sent in the API Configuration.
  • Choose the POST version with JSON instead of GET to avoid exposing sensitive data.
  • Handle errors by validating the API response codes and logging failures for auditing.
  • Configure your account for maximum efficiency and to avoid sending incorrect messages:

  • Ensure that the anti-duplicate filter is enabled to avoid sending identical messages to the same recipient.
  • Activate the country filter by adding the allowed countries to your account. This way, messages sent to other countries are discarded.
  • Set the time filter to send messages only during appropriate hours.
  • Enable automatic recharges so the account never runs out of credits and automated sending does not stop.
  • Check your user notification settings to stay up to date with news, alerts, and events for your account.
  • Common use cases

  • Medical appointment reminders: Automatically send an SMS to remind the patient of their next appointment, reducing no-shows and improving schedule management.
  • Order confirmations: Notify the client of their purchase status (received, prepared, shipped, or delivered), providing transparency and peace of mind during the buying process.
  • Security alerts: Instantly inform about changes, suspicious access, or account lockouts, reinforcing platform trust and protection.
  • Event notifications: Communicate details of webinars, workshops, or in-person events (time, location, or access link) to ensure punctual and organized attendance.
  • Verification codes (OTP): Send a one-time code to complete authentication or password reset processes, adding an extra layer of security.
  • Promotions and flash offers: Launch marketing campaigns with real-time discounts and limited-time promotions, boosting conversions and customer loyalty.
  • Conclusion

    Implementing SMS sending with Python and LabsMobile is a quick and secure process that improves communication with users through instant notifications. With this guide and the provided examples, you will be able to integrate this functionality into any Python application in just a few minutes.

    Discover how SMS sending with Python can optimize your communication processes. Contact us and take the next step towards efficiency!

    You can learn more about how to configure an API in the following links:

    https://www.labsmobile.com/es/api-sms

    https://www.labsmobile.com/es/api-sms/ejemplos-codigo/python

    https://www.labsmobile.com/es/api-sms/versiones-api/http-rest-post-json

    https://www.labsmobile.com/es/api-sms/plugins-modulus

    https://www.labsmobile.com/es/video-tutoriales/integracion-sms-api

    https://www.labsmobile.com/es/api-sms/librerias-sdk

    Our team advises you

    Interested in our services?

    Our managers and technical team are always available to answer all your questions about our SMS solutions and to advise you on the implementation of any action or campaign.

    Contact us