SMS

4 Ways to Send Text messages (SMS) with Python Using Twilio, Amazon SNS, Vonage and SuprSend API

Anjali Arya
February 18, 2024
How to send SMS using Twilio API, Amazon SNS API, Vonage API and SuprSend API. Find out the step-by-step tutorial to send SMS using the provider APIs.
TABLE OF CONTENTS

On an average around 23 billion texts are sent in a day, amounting to 270,000 texts per second. A lot of them consist of alerts and information that companies send their users.

This blog will list 4 major ways of sending text messages (SMS) using python through different service providers, with a comprehensive code guide for each to get you started with your SMS needs.

Text SMS are broadly done in two prominent ways, either by installing SDKs of the SMS providers or by using their pre-established APIs. 

Let’s start with a well known company for the Service, Twilio.

Twilio API 

Twilio provides a programmable SMS API service served over HTTPs. Twilio’s API enables the user to  send and receive SMS messages, track the delivery of sent messages, and even schedule SMS messages to be sent at a later time.

Twilio is a very well established company and is known for their SMS provision, and is often celebrated as a bargain in accordance with Twilio’s pricing for its service.

Why use Twilio API to send SMS?

Most popular, Used by a lot of high value companies over multiple nations, support, guided documentation.

Why not to use Twilio API to send SMS?

Costly, lacks in the quality of analytical data sourced from engagement with the SMS sent.

Prerequisites

All you need to do before getting started is sign up on twilio, select a number that suits your needs, and just write the code:

The four questions you need to know before buying a twilio number

Python code walkthrough

  1. First download Twilio's own CLI here
  2. Download Twilio’s helper library by running the command- pip install twilio in the terminal.
  3. Paste the following code and copy your authorization token and account SID which are visible on your twilio dashboard.
  4. You can use the Twilio CLI or your own python environment to run the following code.
        
            import os
            from twilio.rest import Client
            account_sid = os.environ['TWILIO_ACCOUNT_SID']
            auth_token = os.environ['TWILIO_AUTH_TOKEN']
            client = Client(account_sid, auth_token)

            message = client.messages.create(
                                          body='This is awesome',
                                          from_='+15017122661',
                                          to='+15558675310'
                                      )

            print(message.sid)
        
    

Replace the number you want to send it to in the to section the number that you just purchased to the from section.

Amazon SNS 

AWS SNS has a unique structure for sending SMS. A topic is basically a collection of users that will get notified of your published messages, they can be users that you can choose to subscribe to the topic or not. You can also publish directly to a particular mobile phone, and both of these can be done either by the SNS SDK by Amazon or by the console of Amazon SNS.

The user can create, manage and subscriptions for their SMS texts.

Why use SNS API to send SMS?

Amazon has a unique no charges policy for 1 million requests (batched by size) each month, which makes it a comparatively inexpensive notification provider, using SNS contributes to the AWS credits provided to startups. Hence it becomes a good choice for startups.

Why not to use SNS API to send SMS?

There have been reports that SNS sometimes fails to notify their users when certain providers are down.

There are two ways of sending SMS using Amazon SNS, one is through publishing a message to a Topic or publishing to a mobile phone. We will use the AWS SDK to send an SMS to a phone number.

Prerequisites to send an SMS using Amazon SNS:

Install AWS python SDK on your PC, Sign Up on SNS and buy the number that suits your needs.

Code Walkthrough:

        
            class SnsWrapper:
                """Encapsulates Amazon SNS topic and subscription functions."""
                def __init__(self, sns_resource):

                    self.sns_resource = sns_resource

                def publish_text_message(self, phone_number, message):
                    try:
                        response = self.sns_resource.meta.client.publish(
                            PhoneNumber=phone_number, Message=message)
                        message_id = response['MessageId']
                        logger.info("Published message to %s.", phone_number)
                    except ClientError:
                        logger.exception("Couldn't publish message to %s.", phone_number)
                        raise
                    else:
                        return message_id
        
    

Vonage API

Vonage offers flexible and scalable voice, messaging, video and data capabilities across Unified Communications, Contact Centers and Communications APIs. Vonage provides a robust SMS API for its users that can help them send and receive messages in high volumes, and receive SMS using local numbers.

Why use Vonage API to send SMS?

Cost effective solutions for small businesses, simple to use UI, local and international network, high deliverability and success rates,capability to increase volume of messaging APIs and extends to a global reach.

Why not to use Vonage API to send SMS?

Provides chat only support, Additional features such as images, VOIP, cost extra.

Prerequisites for Vonage API

Register your brand and apply for its vetting, then register your campaign and link a number to it.

Code walkthrough:

  • First install the dependencies using the ~pip install vonage command on your terminal.
  • Create a file named ‘send-an-sms.py’ and write the following code
  • To send an SMS, replace the following variables in the example below:
  1. VONAGE_API_KEY: Your Vonage API key (see it on your dashboard).
  2. VONAGE_API_SECRET: Your Vonage API secret (also available on your dashboard).
  3. VONAGE_BRAND_NAME: The alphanumeric string that represents the name or number of the organisation sending the message.
  4. TO_NUMBER: The phone number you are sending the message to.
        
            responseData = client.sms.send_message(
                {
                    "from": VONAGE_BRAND_NAME,
                    "to": TO_NUMBER,
                    "text": "This text message is a SECRET one",
                }
            )

            if responseData["messages"][0]["status"] == "0":
                print("Message sent successfully.")
            else:
                print(f"Message failed with error: {responseData['messages'][0]['error-text']}")
        
    

That's it! You have sent your first message through the Vonage API.

SuprSend 

Suprsend, provides services that end the difficulties faced by a growing business using the services of these SMS service providers.

Through SuprSend’s Python SDK, you can communicate with your subscribers over multiple channels with just a single trigger. SuprSend’s notification architecture sits on top of all of these SMS providers, with all infrastructure setup done to send notifications and receive delivery reports.

Why use Suprsend to send SMS?

You don’t need to worry about changing your SMS configuration as per the compliances of different countries. What makes Suprsend standout is it’s multi-channel API,  which can also trigger notifications over various channels and gives immediate, actionable, and insightful data analytics. Suprsend boasts an intuitive UI that enables people with no prior programming experience to use its no-code architecture setup,Suprsend has great documentation, and great support on slack,email and chat.

Let’s quickly go through a guide to send your first notification using Python SDK.

Setup and Walkthrough 

Let’s walk you through the steps of setting up and using the python SDK of Suprsend.

Prerequisites to use Suprsend:-

Sign up on Suprsend, Integrate your Python SDK, Create a user profile and you’re through!

Done with the setup, let’s code!

First let’s get a high level understanding of how Suprsend works. You create a workflow, and then put details into the following code snippet which contains information on the name of the workflow, the template name, the category of notification that is generated by the workflow like transactional or maybe promotional messages. You would also notice the “$channels” list which contains all the channels preference set by the users themselves or by the business.

Let’s trigger the Workflow from SuprSend API.

        
            from suprsend import Workflow
            # Prepare Workflow body
            workflow_body = {
              "name": "workflow_name",
              "template": "template_slug",
              "notification_category": "notification_category", # notification category #transactional/promotional/system
              "delay": "time_delay",  # time delay after which the first notification will # be sent
              "users": [
                {
                  "distinct_id": "distinct_id", # unique identifier of the user
                  # if $channels is present, communication will be triggered on mentioned channels only.
                  # "$channels": [“email”, “sms”],
                  # User communication channel can be added as [optional]:
                  "$sms":["+15555555555"],
                }
              ],

            # data can be any json / serializable python-dictionary
              "data": {
                "key":"value",
                "nested_key": {
                  "nested_key1": "some_value_1",
                  "nested_key2": {
                    "nested_key3": "some_value_3",
                  },
                }
              }

            }   
            wf = Workflow(body=workflow_body)
            # Trigger workflow
            response = supr_client.trigger_workflow(wf)
            print(response)
        
    

That’s it! We have triggered the workflow from our Backend SDK and sent SMS from the code. It’s really helpful how Suprsend makes it so easy to switch vendors and sits on the layer between Vendors and Customers to make common nuances faced by a growing business disappear.

Written by:
Anjali Arya
Product & Analytics, SuprSend
ABOUT THE AUTHOR

What’s a Rich Text element?

The rich text element allows you to create and format headings, paragraphs, blockquotes, images, and video all in one place instead of having to add and format them individually. Just double-click and easily create content.

Static and dynamic content editing

A rich text element can be used with static or dynamic content. For static content, just drop it into any page and begin editing. For dynamic content, add a rich text field to any collection and then connect a rich text element to that field in the settings panel. Voila!

How to customize formatting for each rich text

Headings, paragraphs, blockquotes, figures, images, and figure captions can all be styled after a class is added to the rich text element using the "When inside of" nested selector system.

Implement a powerful stack for your notifications
By clicking “Accept All Cookies”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. View our Privacy Policy for more information.