Java sms sending code

Sending SMS in Java with Twilio

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Читайте также:  Python and linux shell

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

We’re looking for a new Java technical editor to help review new articles for the site.

1. Introduction

Sending SMS messages is a big part of many modern applications. There are a variety of uses cases that SMS messages can serve: two-factor authentication, real-time alerts, chatbots, and many more.

In this tutorial, we’ll build a simple Java application that sends SMS messages using Twilio.

There are a number of services that provide SMS capabilities, such as Vonage, Plivo, Amazon Simple Notification Service (SNS), Zapier, and more.

Using the Twilio Java client, we can send an SMS message in just a few lines of code.

2. Setting up Twilio

To get started we’ll need a Twilio account. They offer a trial account that is sufficient for testing every feature of their platform.

As part of the account setup, we must also create a phone number. This is important because the trial account requires a verified phone number for sending messages.

Twilio offers a quick setup tutorial for new accounts. Once we complete the account setup and verify our phone number, we can start sending messages.

3. Introduction to TwiML

Before we write our sample application, let’s take a quick look at the data exchange format used for Twilio services.

Читайте также:  Java security settings system

TwiML is a proprietary markup language based on XML. The elements in a TwiML message mirror the different actions we can take related to telephony: make a phone call, record a message, send a message, and so on.

Here is an example TwiML message for sending an SMS:

And here is another example TwiML message that makes a phone call:

These are both trivial examples, but they give us a good understanding of how TwiML looks like. It’s composed of verbs and nouns that are easy to remember and directly relate to the action we’d perform with a phone.

4. Sending SMS in Java with Twilio

Twilio provides a rich Java client that makes interacting with their services easy. Instead of having to write code that builds TwiML messages from scratch, we can use an out-of-the-box Java client.

4.1. Dependencies

We can download the dependency directly from Maven Central or by adding the following entry to our pom.xml file:

4.2. Sending an SMS

To get started, let’s look at some sample code:

Twilio.init(ACCOUNT_SID, AUTH_TOKEN); Message message = Message.creator( new PhoneNumber("+12225559999"), new PhoneNumber(TWILIO_NUMBER), "Sample Twilio SMS using Java") .create();

Let’s break down into key pieces the code in the above sample:

  • The Twilio.init() call is required once to set up the Twilio environment with our unique Account Sid and Token
  • The Message object is the Java equivalent to the TwiML element we saw earlier
  • Message.creator() requires 3 parameters: To phone number, From phone number, and the message body
  • The create() method handles sending the message

4.3. Sending an MMS

The Twilio API also supports sending multimedia messages. We can mix and match text and images, for this to work the receiving phone must support media messaging:

Twilio.init(ACCOUNT_SID, AUTH_TOKEN); Message message = Message.creator( new PhoneNumber("+12225559999"), new PhoneNumber(TWILIO_NUMBER), "Sample Twilio MMS using Java") .setMediaUrl( Promoter.listOfOne(URI.create("http://www.domain.com/image.png"))) .create();

5. Tracking Message Status

In the previous examples, we didn’t confirm if the message was actually delivered. However Twilio provides a mechanism for us to determine whether a message was successfully delivered or not.

5.1. Message Status Codes

When sending a message, it’ll have one of the statuses at any time:

  • Queued – Twilio has received the message and queued it for delivery
  • Sending – the server is in the process of dispatching your message to the nearest upstream carrier in the network
  • Sent – the message was successfully accepted by the nearest upstream carrier
  • Delivered – Twilio has received confirmation of message delivery from the upstream carrier, and possibly the destination handset when available
  • Failed – the message couldn’t be send
  • Undelivered – the server has received a delivery receipt indicating the message wasn’t delivered

Note that for the last two statuses we can find an error code with more specific details to help us troubleshoot delivery problems.

The Twilio Java Client offers a synchronous and asynchronous methods to fetch status. Let’s have a look.

5.2. Checking Delivery Status (Synchronous)

Once we’ve created a Message object, we can call Message.getStatus() to see which status it’s currently in:

Twilio.init(ACCOUNT_SID, AUTH_TOKEN); ResourceSet messages = Message.reader().read(); for (Message message : messages)

Note that Message.reader().read() makes a remote API call so use it sparingly. By default, it returns all messages we’ve sent, but we can filter the returned messages by phone numbers or date range.

5.3. Checking Delivery Status (Async)

Because retrieving message status requires a remote API call, it can take a long time. To avoid blocking the current thread, the Twilio Java client provides also an asynchronous version of Message.getStatus().read().

Twilio.init(ACCOUNT_SID, AUTH_TOKEN); ListenableFuture> future = Message.reader().readAsync(); Futures.addCallback( future, new FutureCallback>() < public void onSuccess(ResourceSetmessages) < for (Message message : messages) < System.out.println(message.getSid() + " : " + message.getStatus()); >> public void onFailure(Throwable t) < System.out.println("Failed to get message status: " + t.getMessage()); >>);

This uses the Guava ListenableFuture interface to process the response from Twilio on a different thread.

6. Conclusion

In this article, we learned how to send SMS and MMS using Twilio and Java.

While TwiML is the basis of all messages to and from Twilio servers, the Twilio Java client makes sending messages incredibly easy.

And, as always, the full codebase for this example can be found in our GitHub repository.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Оцените статью