How to send sms from Kotlin
The simplest way to send SMS from Kotlin 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 an 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 an HTTP 200 OK response to your request. (Figure 1)
Kotlin code to send sms to mobile
The Kotlin SMS code sample below demonstrates how you can send SMS using the http rest SMS API of Ozeki SMS Gateway using the Kotlin Ozeki.Libs.Rest library. This library is provided to you free of charge, and you may use it and modify it in any of your projects.
MainActivity.kt
package send.sms import android.os.Build import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.text.method.ScrollingMovementMethod import androidx.annotation.RequiresApi import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import Ozeki.Libs.Rest.Configuration import Ozeki.Libs.Rest.Message import Ozeki.Libs.Rest.MessageApi class MainActivity : AppCompatActivity() { @RequiresApi(Build.VERSION_CODES.O) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val btnSendRequest:android.widget.Button = findViewById(R.id.btnSendRequest) val inputToAddress:android.widget.EditText = findViewById(R.id.inputToAddress) val inputMessage:android.widget.EditText = findViewById(R.id.inputMessage) val logBox:android.widget.TextView = findViewById(R.id.logBox) logBox.movementMethod = ScrollingMovementMethod() val configuration = Configuration( username = "http_user", password = "qwe123", apiurl = "http://10.0.2.2:9509/api" ) val api = MessageApi(configuration) btnSendRequest.setOnClickListener { if (inputToAddress.text.toString() != "" && inputMessage.text.toString() != "") { GlobalScope.launch(Dispatchers.IO) { val msg = Message() msg.ToAddress = inputToAddress.text.toString() msg.Text = inputMessage.text.toString() inputToAddress.text.clear() inputMessage.text.clear() val response = api.Send(msg) logBox.text = String.format("%s\n%s", logBox.text, response.toString()) } } } } }
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="send.sms.MainActivity"> <Button android:id="@+id/btnSendRequest" android:layout_width="320dp" android:layout_height="50dp" android:layout_marginBottom="24dp" android:text="Send" android:backgroundTint="#FF3F3F" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.505" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/logBox" app:layout_constraintVertical_bias="0.776" /> <EditText android:id="@+id/inputMessage" android:layout_width="320dp" android:layout_height="150dp" android:layout_marginTop="32dp" android:ems="10" android:gravity="start|top" android:hint="Hello world!" android:inputType="textMultiLine" android:textColorHint="#BFBFBF" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.494" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView" /> <TextView android:id="@+id/textView" android:layout_width="320dp" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:text="Message:" android:textSize="20sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.505" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/inputToAddress" /> <TextView android:id="@+id/textView2" android:layout_width="320dp" android:layout_height="wrap_content" android:layout_marginTop="40dp" android:text="To Address:" android:textSize="20sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.505" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <EditText android:id="@+id/inputToAddress" android:layout_width="320dp" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:ems="10" android:hint="+36201111111" android:inputType="textPersonName" android:textColorHint="#BFBFBF" android:textSize="18sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.505" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView2" /> <TextView android:id="@+id/logBox" android:layout_width="320dp" android:layout_height="160dp" android:layout_marginTop="36dp" android:scrollbars="vertical" android:text="Log:" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.505" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/inputMessage" /> </androidx.constraintlayout.widget.ConstraintLayout>
How to use the Kotlin sms example:
You can use the Message class to create the SMS and 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.kt
The source code explained in this article can be downloaded and used and modified free of charge.
Download: SendSms.kt.zip (148Kb)
What is in the SendSms.kt.zip file?
The SendSms.kt.zip file contains the example project, which has the Ozeki.Libs.Rest library in it. With this library, you can send, delete, mark and receive SMS messages by creating a MessageApi and using the Send(), Delete(), Mark(), and Receive() methods. (Figure 2)
How to send SMS from Kotlin (Quick steps)
To send sms from Kotlin:
- Install Ozeki SMS Gateway
- Connect Ozeki SMS Gateway to the mobile network
- Send a test sms from Ozeki GUI
- Create a HTTP sms api user
- Android Studio
- Download the example project above
- Create the SMS by creating a new Message object
- Create an api to send your message
- Use the Send method to send your message
- Read the response message on the console
- Check the logs in the SMS gateway
Install Ozeki SMS Gateway and create an HTTP API user
To be able to send SMS from Kotlin, first you need to install Ozeki SMS Gateway. The SMS gateway can be installed on the same computer, where you develop your Kotlin code in Android Studio. 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 works without modification.
After the environment is setup, you can run your Kotlin code.
HTTP API url to use send sms from Kotlin
To send SMS from Kotlin, your Kotlin 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 with the IP address of your SMS gateway. If Ozeki SMS Gateway is installed on the same computer where the JavaScript 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 Kotlin
To authenticate the Kotlin SMS client, you need to send the username and password in a base64 encoded string to the server in an HTTP request. The format used is: base64(username+":"+password). In Kotlin you can use the following code to do this encoding:
var usernamePassword = "%s:%s".format(username, password) return "Basic %s".format(Base64.getEncoder().encodeToString(usernamePassword.toByteArray()))
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 Kotlin
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 Kotlin
To submit the SMS, your Kotlin application will send an HTTP request similar to the one below. Note, that this request contains an HTTP header part and a http body part. The HTTP body is a JSON encoded data string. It contains the recipient number and the text of the messages.
POST /api?action=sendmsg HTTP/1.1 Connection: Keep-Alive Content-Length: 323 Content-Type: application/json; charset=utf-8 Accept-Encoding: gzip Authorization: Basic aHR0cF91c2VyOnF3ZTEyMw== Host: 10.0.2.2:9509 User-Agent: okhttp/4.2.2 { "messages": [ { "message_id": "b686acf6-7420-4a3d-b444-779dcffc652b", "to_address": "+36201111111", "text": "Hello world!", "create_date": "2021-06-17T09:48:30", "valid_until": "2021-06-24T09:48:30", "time_to_send": "-999999999-01-01T00:00", "submit_report_requested": true, "delivery_report_requested": true, "view_report_requested": true } ] }
HTTP response received by the Kotlin sms example
Once the SMS gateway receives this request, it will generate an 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.120 (www.myozeki.com) Content-Type: application/json; charset=utf8 Last-Modified: Wed, 16 Jun 2021 09:06:03 GMT Server: 10/10.3.120 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": "b686acf6-7420-4a3d-b444-779dcffc652b", "from_station": "%", "to_address": "+36201111111", "to_station": "%", "text": "Hello world!", "create_date": "2021-06-17 09:48:30", "valid_until": "2021-06-24 09:48:30", "time_to_send": "2021-06-17 09:48:30", "submit_report_requested": true, "delivery_report_requested": true, "view_report_requested": false, "tags": [ { "name": "Type", "value": "SMS:TEXT" } ], "status": "SUCCESS" } ] } }
How to send SMS from Kotlin using the sms api and the example project above (Video tutorial)
This video shows you how to download and use the SendSms.kt project. Once you opened the example project, you might notice that there is a package called Ozeki.Libs.Rest This is the package that contains the MessageApi and all the stuff you need to send an SMS using Kotlin.
How to check that the SMS has been accepted by the HTTP user
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. At the end of the video above you can see how to check if the request has been received by the http_user. (Figure 3)
How using the app looks like
On Figure 4, you can see how the app looks like after you sent a message with it. As you can see your previously sent messages will be stored as a log under the 'Message' textbox. You can see all the information about the message like the sender, the text, and the result of the sending procedure.
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.
How to add Ozeki.Libs.Rest to your own project
The Ozeki.Libs.Rest library can be downloaded and used and modified free of charge.
Download: Ozeki.Libs.Rest.kt.zip (7.66Kb)
If you decide to create your application on your own only with the Ozeki.Libs.Rest
library, there are few things you should change in your base application.
In order to use the Ozeki.Libs.Rest library you have to put it into the java folder
of the main directory
In the following video, I will show you how to download and add the Ozeki.Libs.Rest
library to your own project.
Dependencies
It is important to mention, that the Ozeki.Libs.Rest library has some dependencies. In order to use it, you have to add these dependencies into the Gradle Scripts.
implementation "com.squareup.okhttp3:okhttp:4.2.2" implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0' implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0'
Adding the dependencies (video tutorial)
In the following video, you will learn how to add the previously mentioned dependencies. It will start with copying the code and will take you all the way to the successfully added dependencies. The video is only 53 seconds long, but it features all the needed steps to complete the process. You can follow this tutorial with no effort.
Internet access
In order to make it possible for your application to send
an HTTP request, you have to enable your application
to connect to the internet.
In the following video, I'll show you how to enable internet access
for your Kotlin application.
<uses-permission android:name="android.permission.INTERNET" />
android:usesCleartextTraffic="true"
How to enable internet connection for your app (Video tutorial)
You need to add both of these lines to the AndroidManifest.xml file. In the following video, I'll show you where you should put the codes above. The video will start with copying the code and will take you to the successfully added internet connection. This video is detailed and offers an easy time following it.
Conclusion
The purpose of this guide was to show you how to send SMS messages from Kotlin with the HTTP SMS API of the Ozeki SMS Gateway. This knowledge you learned grants the ability to keep in touch with your customers using a plain Kotlin code. International messaging is possible with the Ozeki SMS Gateway too, because it works in any country and can send and receive SMS through various mobile connections.
Make sure that you continue your studies here, visit other tutorial pages on the Ozeki website for more information. Check out more guides about using Kotlin, start with the How to send multiple SMS from Kotlin one.
Now your first thing to do is to download the Ozeki SMS Gateway and start using it!
More information
- Kotlin send SMS with the HTTP rest API (code sample)
- Kotlin send multiple SMS with the HTTP rest API (code sample)
- Kotlin schedule SMS with the HTTP rest API (code sample)
- Kotlin receive SMS with the HTTP rest API (code sample)
- Kotlin delete SMS with the HTTP rest API (code sample)
- Github: Kotlin SMS API