Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send SMS in Java

Tags:

java

sms

People also ask

How can I send free SMS using Java program?

Example – Sending a text message to a specific application port for a Java applet running on the phone: sendsms. init(); sendsms. server = "http://127.0.0.1:8800/"; sendsms.

How do I send a text with spring boot?

Create a new Spring Boot Project Go to the Download directory and extract the zipped folder. Now open your Spring Tool Suite. Click on File -> Import -> Existing Maven Projects. Navigate to the Download directory where you have the extracted project and click on the Finish button.


(Disclaimer: I work at Twilio)

Twilio offers a Java SDK for sending SMS via the Twilio REST API.


if all you want is simple notifications, many carriers support SMS via email; see SMS through E-Mail


There is an API called SMSLib, it's really awesome. http://smslib.org/

Now you have a lot of Saas providers that can give you this service using their APIs

Ex: mailchimp, esendex, Twilio, ...


The best SMS API I've seen in Java is JSMPP. It is powerful, easy to use, and I used it myself for an enterprise-level application (sending over 20K SMS messages daily).

This API created to reduce the verbosity of the existing SMPP API. It's very simple and easy to use because it hides the complexity of the low level protocol communication such as automatically enquire link request-response.

  • https://code.google.com/p/jsmpp/

I've tried some other APIs such as Ozeki, but most of them either is commercial or has limitation in its throughput (i.e can't send more than 3 SMS messages in a second, for example).


You Can Do this With A GSM Modem and Java Communications Api [Tried And Tested]

  1. First You Need TO Set Java Comm Api

    This Article Describes In Detail How to Set Up Communication Api

  2. Next You Need A GSM Modem (preferably sim900 Module )

  3. Java JDK latest version preferable

  4. AT Command Guide

    Code

    package sample;

        import java.io.*;
        import java.util.*;
    
        import gnu.io.*;
    
        import java.io.*;
    
    
        import org.apache.log4j.chainsaw.Main;
    
        import sun.audio.*;
    
        public class GSMConnect implements SerialPortEventListener, 
         CommPortOwnershipListener {
    
         private static String comPort = "COM6"; // This COM Port must be connect with GSM Modem or your mobile phone
         private String messageString = "";
         private CommPortIdentifier portId = null;
         private Enumeration portList;
         private InputStream inputStream = null;
         private OutputStream outputStream = null;
         private SerialPort serialPort;
         String readBufferTrial = "";
         /** Creates a new instance of GSMConnect */
         public GSMConnect(String comm) {
    
           this.comPort = comm;
    
         }
    
         public boolean init() {
           portList = CommPortIdentifier.getPortIdentifiers();
           while (portList.hasMoreElements()) {
             portId = (CommPortIdentifier) portList.nextElement();
             if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
               if (portId.getName().equals(comPort)) {
                   System.out.println("Got PortName");
                 return true;
               }
             }
           }
           return false;
         }
    
         public void checkStatus() {
           send("AT+CREG?\r\n");
         }
    
    
    
         public void send(String cmd) {
           try {
             outputStream.write(cmd.getBytes());
           } catch (IOException e) {
             e.printStackTrace();
           }
         }
    
         public void sendMessage(String phoneNumber, String message) {
               char quotes ='"';
           send("AT+CMGS="+quotes + phoneNumber +quotes+ "\r\n");
           try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
            //   send("AT+CMGS=\""+ phoneNumber +"\"\r\n");
           send(message + '\032');
           System.out.println("Message Sent");
         }
    
         public void hangup() {
           send("ATH\r\n");
         }
    
         public void connect() throws NullPointerException {
           if (portId != null) {
             try {
               portId.addPortOwnershipListener(this);
    
               serialPort = (SerialPort) portId.open("MobileGateWay", 2000);
               serialPort.setSerialPortParams(115200,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
             } catch (PortInUseException | UnsupportedCommOperationException e) {
               e.printStackTrace();
             }
    
             try {
               inputStream = serialPort.getInputStream();
               outputStream = serialPort.getOutputStream();
    
             } catch (IOException e) {
               e.printStackTrace();
             }
    
             try {
               /** These are the events we want to know about*/
               serialPort.addEventListener(this);
               serialPort.notifyOnDataAvailable(true);
               serialPort.notifyOnRingIndicator(true);
             } catch (TooManyListenersException e) {
               e.printStackTrace();
             }
    
        //Register to home network of sim card
    
             send("ATZ\r\n");
    
           } else {
             throw new NullPointerException("COM Port not found!!");
           }
         }
    
         public void serialEvent(SerialPortEvent serialPortEvent) {
           switch (serialPortEvent.getEventType()) {
             case SerialPortEvent.BI:
             case SerialPortEvent.OE:
             case SerialPortEvent.FE:
             case SerialPortEvent.PE:
             case SerialPortEvent.CD:
             case SerialPortEvent.CTS:
             case SerialPortEvent.DSR:
             case SerialPortEvent.RI:     
             case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
             case SerialPortEvent.DATA_AVAILABLE:
    
               byte[] readBuffer = new byte[2048];
               try {
                 while (inputStream.available() > 0) 
                 {
                   int numBytes = inputStream.read(readBuffer);
    
                   System.out.print(numBytes);
                   if((readBuffer.toString()).contains("RING")){
                   System.out.println("Enter Inside if RING Loop");    
    
    
    
                   }
                 }
    
                 System.out.print(new String(readBuffer));
               } catch (IOException e) {
               }
               break;
           }
         }
         public void outCommand(){
             System.out.print(readBufferTrial);
         }
         public void ownershipChange(int type) {
           switch (type) {
             case CommPortOwnershipListener.PORT_UNOWNED:
               System.out.println(portId.getName() + ": PORT_UNOWNED");
               break;
             case CommPortOwnershipListener.PORT_OWNED:
               System.out.println(portId.getName() + ": PORT_OWNED");
               break;
             case CommPortOwnershipListener.PORT_OWNERSHIP_REQUESTED:
               System.out.println(portId.getName() + ": PORT_INUSED");
               break;
           }
    
         }
         public void closePort(){
    
            serialPort.close(); 
         }
    
         public static void main(String args[]) {
           GSMConnect gsm = new GSMConnect(comPort);
           if (gsm.init()) {
             try {
                 System.out.println("Initialization Success");
               gsm.connect();
               Thread.sleep(5000);
               gsm.checkStatus();
               Thread.sleep(5000);
    
               gsm.sendMessage("+91XXXXXXXX", "Trial Success");
    
               Thread.sleep(1000);
    
               gsm.hangup();
               Thread.sleep(1000);
               gsm.closePort();
               gsm.outCommand();
               System.exit(1);
    
    
             } catch (Exception e) {
               e.printStackTrace();
             }
           } else {
             System.out.println("Can't init this card");
           }
         }
    
    
            }
    

You can use Nexmo to send SMS as well as receive SMS.

Sending SMS with the Nexmo Java Library is fairly straightforward. After creating a new account, renting a virtual number, and getting your API key & secret you can use the library to send SMS like so:

  public class SendSMS {

      public static void main(String[] args) throws Exception {
          AuthMethod auth = new TokenAuthMethod(API_KEY, API_SECRET);
          NexmoClient client = new NexmoClient(auth);

          TextMessage message = new TextMessage(FROM_NUMBER, TO_NUMBER, "Hello from Nexmo!");

          //There may be more than one response if the SMS sent is more than 160 characters.
          SmsSubmissionResult[] responses = client.getSmsClient().submitMessage(message);
            for (SmsSubmissionResult response : responses) {
            System.out.println(response);
          }
      }
  }

To receive SMS you'll need to set up a server that consumes a webhook. That's fairly simple as well. I recommend checking out our tutorial on receiving SMS with Java.

Disclosure: I work for Nexmo