How to send multiple sms from Python flask

The most simple way to send SMS from Python flask is to use the built in HTTP/Rest SMS api of Ozeki SMS Gateway. When you use this API, you will send SMS messages by issuing a HTTP Post request to the SMS gateway. The HTTP Post request will contain a message formatted in json format. The SMS gateway will send this SMS to the recipient phone, and it will return a HTTP 200 OK response to your request.

how to send multiple sms from python flask
Figure 1 - How to send multiple sms from Python flask

Python code to send sms to mobile

The Python sms code sample below demonstrates how you can send SMS using the http rest sms api of Ozeki SMS Gateawy using the Python ozekilibsrest library. This library is provided to you free of charge, and you may use it and modify it in any of your projects.

SendMultipleSms.py

		from flask import Flask, render_template, request
		from ozekilibsrest import Configuration, Message, MessageApi
		
		app = Flask(__name__)
		
		configuration = Configuration(
		    username="http_user",
		    password="qwe123",
		    api_url="http://127.0.0.1:9509/api"
		)
		
		api = MessageApi(configuration)
		
		messages_to_send = []
		logs = []
		
		
		@app.route('/', methods=['GET', 'POST'])
		def index():
		    if request.method == 'POST':
		        if request.form['submit'] == 'SEND' and len(messages_to_send) > 0:
		            log = api.send(messages_to_send)
		            logs.append(log)
		            messages_to_send.clear()
		        elif request.form['submit'] == 'ADD':
		            message = Message(
		                to_address=request.form['to_address'],
		                text=request.form['text']
		            )
		            messages_to_send.append(message)
		    return render_template('SendMultipleSms.html', logs=logs, messages=messages_to_send)
		
		
		if __name__ == '__main__':
		    app.run()
	

Code 1 - SendMultipleSms.py

SendMultipleSms.html

		<!DOCTYPE html>
		<html lang="en">
		    <head>
		        <meta charset="UTF-8">
		        <title>Send multiple SMS with Ozeki SMS Gateway</title>
		        <link rel="stylesheet"
		        href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
		        integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
		        crossorigin="anonymous">
		    </head>
		    <body>
		        <form action="/" method="POST" class="form-group" style="width: 40%;
		        margin-top: 8vh; margin-left: 30%;
		        display: flex; flex-direction: column; height: 30vh;
		        justify-content: space-evenly;">
		            <b>To address:</b>
		            <input class="form-control" type="text"
		                   name="to_address" placeholder="+36201111111"
		                   autocomplete=false>
		            <b>Text:</b>
		            <input class="form-control"
		                   type="text" name="text"
		                   placeholder="Hello world!"
		                   autocomplete=false>
		            <input class="btn btn-primary"
		                   style="font-weight: 600;"
		                   type="submit"
		                   name="submit"
		                   value="ADD">
		        </form>
		        <ul style="width: 40%; margin-left: 30%;
		        margin-bottom: 30px; height: 20vh; overflow-y: scroll;"
		            class="list-group card">
		            <li class="list-group-item card"><b>Messages:</b></li>
		            {% if messages %}
		                {%for message in messages%}
		                    <li class="list-group-item">{{ message }}</li>
		                {%endfor%}
		            {% endif  %}
		        </ul>
		        <form method="POST" class="form-group"
		        style="width: 40%; margin-left: 30%;
		            display: flex; flex-direction: column;
		            height: auto; justify-content: space-evenly;">
		            <input class="btn btn-primary"
		                   style="font-weight: 600;"
		                   type="submit"
		                   name="submit"
		                   value="SEND">
		        </form>
		        <ul style="width: 40%; margin-left: 30%;
		        margin-top: 30px; height: 20vh;
		        overflow-y: scroll;"
		            class="list-group card">
		            <li class="list-group-item card"><b>Logs:</b></li>
		            {% if logs %}
		                {%for log in logs%}
		                    <li class="list-group-item">{{ log }}</li>
		                {%endfor%}
		            {% endif  %}
		        </ul>
		    </body>
		</html>
	

Code 2 - SendMultipleSms.html

How to use the Python flask sms example:

This Python flask sms example can be used in any Python application. To use it, you must to install the ozekilibsrest package with the pip install ozekilibsrest command adn the flask package with pip install flask command. After the packages are installed you must put the from ozekilibsrest import Configuration, Message, MessageApi directive and the from flask import Flask, render_template, request into the header section of your Python source code. This will allow you to use the classes provided by the ozekilibsrest library. You can use the Message class to create the SMS. You can use the MessageApi class to send the SMS to the SMS gateway. The SMS gateway will forward your message to the mobile network either through a wireless connection or through the Internet.

Download SendMultipleSms.py

The source code explained in this article can be downloaded and used and modified free of charge.
Download: SendMultipleSms.py.zip (1.65Kb)

What is in the SendMultipleSms.py folder?

The SendMultipleSms.py folder contains the script of the python flask sms example which will show you how to send multiple SMS messages using Python.

send multiple sms py directory
Figure 2 - What is inside SendMultipleSms.py.zip

How to install the ozekilibsrest library

In order to install the ozekilibsrest library you have to open the command prompt and use the following command. This will install the ozekilibsrest library, and the dependencies it needs.

		pip install ozekilibsrest
	

Code 3 - Command to install the ozekilibsrest library

How to install the flask library

In order to install the flask library you have to open the command prompt and use the following command. This will install the flask library, and the dependencies it needs.

		pip install flask
	

Code 2 - Command to install the flask library

How to send multiple sms from Python flask (Quick steps)

To send multiple sms from Python flask:

  1. Download and install Python
  2. Install the ozekilibsrest library using pip or codna
  3. Install the flask library using pip or codna
  4. Download the SendMultipleSms.py.zip file
  5. Extract the .zip file from Downloads folder
  6. Open the SendMultipleSms.py file in any text editor
  7. Launch Ozeki SMS Gateway
  8. Create a HTTP API user in Ozeki
  9. Run SendMultipleSms.py code using the command prompt to send the test SMS messages
  10. Check the Sent box in Ozeki SMS Gateway

Install Ozeki SMS Gateway and create an HTTP API user

To be able to send SMS from Python, first you need to install Ozeki SMS Gateway. The SMS gateway can be installed on the same computer, where you develop your Python code. After installation, the next step is to connect Ozeki SMS Gateway to the mobile network. You can send a test sms from the Ozeki GUI to verify, that your mobile network connection works. The final step to prepare your environment is to create a HTTP sms api user. Create a user with a username of "http_user", and with a password of "qwe123" to make the example work without modification.

After the environment is setup, you can run your Python code.

HTTP API url to use send sms from Python

To send SMS from Python, your Python will will have to issue an HTTP request to the SMS gateway. The API url is shown below. Note that the IP address (127.0.0.1) should be replaced to the IP address of your SMS gateway. If Ozeki SMS Gateway is installed on the same computer where the Python sms application is running, this can be 127.0.0.1. If it is installed on a different computer it should be the IP address of that computer.

		http://127.0.0.1:9509/api?action=rest
	

HTTP authentication to use send sms from Python

To authenticate the Python sms client, you need to send the username and password in a base64 encoded string to the server in a HTTP request. The format used is: base64(username+":"+password). In Python you can use the following code to do this encoding:

	    def create_authorization_header(username, password):
	        username_password = f'{ username }:{ password }'
	        return f'Basic { b64encode(username_password.encode()).decode() }'
	

For example if you encode the username 'http_user' and the password 'qwe123', you will get the following base64 encoded string: aHR0cF91c2VyOnF3ZTEyMw==.

HTTP request header to send SMS from Python

To send the SMS messages, you need to include the following lines as headers in the HTTP request. Note that we include a content type and an Authorization header.

		Content-Type: application/json
		Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
	

HTTP request to send SMS from Python

To submit the SMS messages, your Python application will send an HTTP request similar to the one below. Note, that this requst contains a HTTP header part and a http body part. The HTTP body is a JSON encoded data string. It contains the recipient numbers and the texts of the messages.

		POST /api?action=sendmsg HTTP/1.1
		Host: 127.0.0.1:9509
		User-Agent: python-requests/2.26.0
		Accept-Encoding: gzip, deflate
		Accept: */*
		Connection: keep-alive
		Authorization: Basic aHR0cF91c2VyOnF3ZTEyMw==
		Content-Type: application/json
		Content-Length: 1027
		
		{
			"messages": [
				{
					"message_id": "cf609600-7269-46e3-ab6e-87ef5a99f848",
					"to_address": "+3620111111",
					"text": "Hello world 1!",
					"create_date": "2021-09-10T15:19:20",
					"valid_until": "2021-09-17T15:19:20",
					"time_to_send": "2021-09-10T15:19:20",
					"submit_report_requested": true,
					"delivery_report_requested": true,
					"view_report_requested": true,
					"tags": []
				},
				{
					"message_id": "8d93e43a-b4dc-493f-a243-10db358a58ec",
					"to_address": "+36202222222",
					"text": "Hello world 2!",
					"create_date": "2021-09-10T15:19:20",
					"valid_until": "2021-09-17T15:19:20",
					"time_to_send": "2021-09-10T15:19:20",
					"submit_report_requested": true,
					"delivery_report_requested": true,
					"view_report_requested": true,
					"tags": []
				},
				{
					"message_id": "35e56437-15e4-4ee7-9ad4-dfc00a8f7c3a",
					"to_address": "+36203333333",
					"text": "Hello world 3!",
					"create_date": "2021-09-10T15:19:20",
					"valid_until": "2021-09-17T15:19:20",
					"time_to_send": "2021-09-10T15:19:20",
					"submit_report_requested": true,
					"delivery_report_requested": true,
					"view_report_requested": true,
					"tags": []
				}
			]
		}
	

HTTP response received by the Python sms example

Once the SMS gateway receives this request, it will generate a HTTP response. The HTTP response will contain a status code, to indicate whether the SMS submit request was successful or not. It will also return a JSON encoded structure to provide you useful details about the messages submission.

		HTTP/1.1 200 OK
		Transfer-Encoding: chunked
		Content-Type: application/json; charset=utf8
		Last-Modified: Fri, 10 Sep 2021 10:22:37 GMT
		Server: 10/10.3.124 Microsoft-HTTPAPI/2.0
		User-Agent: OZEKI 10.3.124 (www.myozeki.com)
		Access-Control-Allow-Origin: *
		Date: Fri, 10 Sep 2021 13:19:19 GMT
		
		{
		  "http_code": 200,
		  "response_code": "SUCCESS",
		  "response_msg": "Messages queued for delivery.",
		  "data": {
		    "total_count": 3,
		    "success_count": 3,
		    "failed_count": 0,
		    "messages": [
		      {
		        "message_id": "cf609600-7269-46e3-ab6e-87ef5a99f848",
		        "from_station": "%",
		        "to_address": "+3620111111",
		        "to_station": "%",
		        "text": "Hello world 1!",
		        "create_date": "2021-09-10 15:19:20",
		        "valid_until": "2021-09-17 15:19:20",
		        "time_to_send": "2021-09-10 15:19:20",
		        "submit_report_requested": true,
		        "delivery_report_requested": true,
		        "view_report_requested": false,
		        "tags": [
		          {
		            "name": "Type",
		            "value": "SMS:TEXT"
		          }
		        ],
		        "status": "SUCCESS"
		      },
		      {
		        "message_id": "8d93e43a-b4dc-493f-a243-10db358a58ec",
		        "from_station": "%",
		        "to_address": "+36202222222",
		        "to_station": "%",
		        "text": "Hello world 2!",
		        "create_date": "2021-09-10 15:19:20",
		        "valid_until": "2021-09-17 15:19:20",
		        "time_to_send": "2021-09-10 15:19:20",
		        "submit_report_requested": true,
		        "delivery_report_requested": true,
		        "view_report_requested": false,
		        "tags": [
		          {
		            "name": "Type",
		            "value": "SMS:TEXT"
		          }
		        ],
		        "status": "SUCCESS"
		      },
		      {
		        "message_id": "35e56437-15e4-4ee7-9ad4-dfc00a8f7c3a",
		        "from_station": "%",
		        "to_address": "+36203333333",
		        "to_station": "%",
		        "text": "Hello world 3!",
		        "create_date": "2021-09-10 15:19:20",
		        "valid_until": "2021-09-17 15:19:20",
		        "time_to_send": "2021-09-10 15:19:20",
		        "submit_report_requested": true,
		        "delivery_report_requested": true,
		        "view_report_requested": false,
		        "tags": [
		          {
		            "name": "Type",
		            "value": "SMS:TEXT"
		          }
		        ],
		        "status": "SUCCESS"
		      }
		    ]
		  }
		}
	

Python sms example: SendMultipleSms.py

How to download the SendMultipleSMS.py project (Video tutorial)

In the following video, you will learn about how you can use the SendMultipleSms.py Python project. The video will start with the download page and will take you all the way to the opened code editor panel. You will learn how to download and open the code file. The video is only 54 second long but it has all the necessary information you need to successfully use the example code file.

Video 1 - How to download and open the solution above

The example code below is part of the SendMultipleSms.py.zip folder.

how to send multiple sms using python
Figure 3 - SendMultipleSms.py

To send an SMS with the example project above, you have to run the python script using the python SendSms.py command. After the script is running you will notice that the command prompt says you have to open the http://127.0.0.1:5000 url. There you can see your first python flask project, which is able to send multiple sms messages to the Ozeki SMS Gateway.

output of the python script
Figure 4 - The output of the SendMultipleSms.py python script

result of the python script
Figure 5 - The SendMultipleSms.html webpage

How to use the project (Video tutorial)

In the following clip, you will see how you can launch the SendMultipleSms.py Python code. The video will start with the opened code and will take you all the way to the events tab with the log of the sent message. You will see how to launch the code and what happened if the code was executed. The video is a little shorter than 1 minute but it contains all the information that is necessary to run the project.

Video 2 - How to use the SendMultipleSms.py script

Conclusion

This article showed the steps of multiple SMS sending in one request from Python flask.

With this knowledge and the provided tools, you should be able to reach out to several customers with one single code. Ozeki SMS Gateway has an important part in this process because this program organizes the message delivery. Ozeki SMS Gateway works with high quality and performance, allowing you to send up to 1000 SMS per second.

Continue your learning in Ozeki's tutorial pages, where you can read about topics like SMS scheduling and deleting in Python.

Now your only thing to do is to download Ozeki SMS Gateway and start working!

More information