Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

How to send text messages using Python

Harsh Jain

Introduction

There are many instances when you may need to sent text messages to your customers or anyone – you can do this very easily using Textbelt and Python.

To do so, we would first need to get an API key from Textbelt. You can follow the steps below to get one:

  1. Visit Textbelt to get your unique API key.
  2. Click on “Create API key”.
  3. Select where you want to send messages (e.g., the US/Canada, Europe, etc.) Then, select your pricing plan and proceed to payment.
  4. After purchasing the API key, you can use the code below to easily send text messages using Python script.

Before moving to the code, lets first install the package required by running:

pip install requests

We are going to use the requests package to hit the https://textbelt.com/text endpoint, that accepts a POST request, with the following parameters:

  • phone: The phone number on which you want to send the message. If you’re in the U.S. or Canada, you can send a normal 10-digit phone number with an area code. If you are outside the U.S., it is best to send the phone number in E.164 format with your country code.
  • message: The content of your SMS.
  • key: Your API key.

Now, take a look at the code:

import requests

payload = {
            'phone': '<PHONE_NUMBER>', 
            'message': '<MESSAGE>', 
            'key':'<API_KEY>'
          }

resp = requests.post('https://textbelt.com/text', payload)

print(resp.json())
Send text messages using Python

Explanation:

  • In line 1, we import the required package.

  • In line 3, we create our payload that will be sent to the Textbelt API.

  • In line 9, we create a POST request to our API and pass the payload.

  • In line 11, we print the response from the API. Now, the endpoint will respond with the JSON:

    • success: whether or not the message was sent successfully (true/false).
    • quotaRemaining: the amount of credit remaining on your API key.
    • textId: the ID of the sent message that we will use to look up its status. This will only be present when success = true.
    • error: A string describing the error that occurred. This will only be present when success = false.

    For example, the response for a message that has been sent successfully would look like this:

    {"success": true, "quotaRemaining": 40, "textId": 12345}
    

    Another example of a response, when we have run out of quota, would look like this:

    {"success": false, "quotaRemaining": 0, "error": "Out of quota"}
    

So, in this way, you can conveniently send text messages, worldwide, using the Python script.

RELATED TAGS

python
communitycreator
RELATED COURSES

View all Courses

Keep Exploring