How to send sms from Python flask
The simplest 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.
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 Gateway 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.
SendSms.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) logs = [] @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'POST': message = Message( to_address=request.form['to_address'], text=request.form['text'] ) log = api.send(message) logs.append(log) return render_template('SendSms.html', logs=logs) if __name__ == '__main__': app.run()
SendSms.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Send 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: 10vh; 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="SEND"> </form> <ul style="width: 40%; margin-left: 30%; height: 40vh; 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>
How to use the Python sms example:
This Python flask sms example can be used in any Python application. To use it, you must install the ozekilibsrest package with the pip install ozekilibsrest command and 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 SendSms.py
The source code explained in this article can be downloaded and used and modified free of charge.
Download: SendSms.py.zip (1.42Kb)
What is in the SendSms.py folder?
The SendSms.py folder contains the script of the python sms example which will show you how to send multiple SMS messages using Python.
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
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
How to send SMS from Python (Simple guidelines)
To send SMS from Python:
- Download and install Python
- Install the ozekilibsrest library using pip or codna
- Install the flask library using pip or codna
- Install a HTTP API user
- Enable Log communication events on the Advanced tab
- Download the SendSMS.py
- Open SendSms.py file in widnows notepad
- Change the data to your own
- Launch Ozeki SMS Gateway app
- Run SendSms.py Python code by open it
- Check the logs to see if the SMS sent
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 in Python IDLE or Notepad. 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 "User1", 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 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==. To send
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, your Python application will send an HTTP request similar to the one below. Note, that this request contains a HTTP header part and a http body part. The HTTP body is a JSON encoded data string. It contains the recipient's number and the message's text.
POST /api?action=sendmsg HTTP/1.1 Connection: Keep-Alive Content-Length: 336 Content-Type: application/json Authorization: Basic aHR0cF91c2VyOnF3ZTEyMw== Host: 127.0.0.1:9509 { "messages": [ { "message_id": "b570dbae-3a05-456d-9dad-a02161b16f1c", "to_address": "+36201111111", "text": "Hello, World!", "create_date": "2021-06-11 11:20:02", "valid_until": "2021-06-18 11:20:02", "time_to_send": "2021-06-11 11:20:02", "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 message's submission.
HTTP/1.1 200 OK User-Agent: OZEKI 10.3.116 (www.myozeki.com) Content-Type: application/json; charset=utf8 Last-Modified: Fri, 11 Jun 2021 11:17:49 GMT Server: 10/10.3.116 Transfer-Encoding: chunked { "http_code": 200, "response_code": "SUCCESS", "response_msg": "Messages queued for delivery.", "data": { "total_count": 1, "success_count": 1, "failed_count": 0, "messages": [ { "message_id": "b570dbae-3a05-456d-9dad-a02161b16f1c", "from_station": "%", "to_address": "+36201111111", "to_station": "%", "text": "Hello, World!", "create_date": "2021-06-11 11:20:02", "valid_until": "2021-06-18 11:20:02", "time_to_send": "2021-06-11 11:20:02", "submit_report_requested": true, "delivery_report_requested": true, "view_report_requested": false, "tags": [ { "name": "Type", "value": "SMS:TEXT" } ], "status": "SUCCESS" } ] } }
Connect your SMS gateway to the mobile network and create an HTTP API user account
We assume, you have already installed Ozeki SMS Gateway, and you have connected it to the mobile network. In order to be able to send SMS to a mobile phone from Python, you need to setup an HTTP API user account in Ozeki SMS Gateway.
Create a new user (Video tutorial)
This video presents you how to setup a new HTTP API user account. It will start with the home page of the Ozeki SMS Gateway and will end with the Events tab of the new user. The video will show you how to create and configure your new user. The great thing about this video is that it is only 30 seconds long but contains all the information you need to create a new http api user.
How to send SMS from Python using the Python sms api (Video tutorial)
This video shows you how to download the SendSms.py.zip file from this page, and how to open the content of the included file in any text editor such as the Windows Notepad. If watch the video, you will notice, that the contents of the SendSms.py zip are placed into the Windows desktop.
Python sms example: SendSms.py
The example code below is part of the SendSms.py.zip file.
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 an sms message to the Ozeki SMS Gateway.
How to check that the SMS has been accepted by the HTTP user (Video tutorial)
After the SMS has been submitted, it is a good idea to check your SMS gateway, to see what it has received. You can check the log by opening the HTTP user's details from the Ozeki SMS Gateway management console. The following video shows you what to look for. The video will start with the opened code and will end with the details of the sent message. You will learn how to launch the project, what the project looks like during running and how the log file looks after it. The video is only 42-seconds-long and easy to understand. You will have no problem following it.
How to check that the SMS has been sent to the mobile network
The final step in verifying the procedure is to take a look at the logs of the mobile network connection. You might have to turn on logging in the configuration of the connection before you send the message to see the logs. If logging is enabled, you will see the phone number and the text of the message you have sent.
Test if the request was accepted (Video tutorial)
In the following video, you will see how to check if the SMPP client was successful in sending your message. You will learn how to open the events tab of the SMPP user and what to look for. The video is only 18 seconds long but will be very helpful.
SMS received on the phone (Video tutorial)
On the following video, you will see how an incoming message looks like that was sent from the Ozeki SMS Gateway. It will start with the home screen of an android phone and will end with the message opened. It is only 18 seconds long and you can see the whole process of receiving a message.
Summary
The guide above explained the steps of sending SMS from Python flask. As it could be seen, Ozeki gives you all the tools needed in message delivery, so if the steps were followed carefully, messaging from Python is no longer an issue. Ozeki SMS Gateway plays enormous part in delivery, you couldn't reach the mobile users without this program. Important to note that Ozeki SMS Gateway works in any country, so messages can be sent internationally with this solution.
Do not finish the reading here, browse Ozeki's tutorial page and learn about multiple SMS sending and SMS receiving in Python.
Your next thing to do is to download Ozeki SMS Gateway and let the work begin!
More information
- Python flask send SMS with the HTTP rest API (code sample)
- Python flask send multiple SMS with the HTTP rest API (code sample)
- Python flask schedule SMS with the HTTP rest API (code sample)
- Python flask receive SMS with the HTTP rest API (code sample)
- Python flask delete SMS with the HTTP rest API (code sample)
- How to download the latest Python flask SMS library from Github