How To Send SMS in Java

In this document I will explain how to use javamail api to send SMS messages throught a gateway (I'll be using ipipi). 

Requirements

First, you will need to include the mail.jar and activation.jar to your project classpath.

Second, add the following method to your application: 

/**
* username: your ipipi account username
* password: your ipipi account password
* body: SMS body
* compression: SMS compression settings. This is optional
* to: Receiver phone number (including country code)
*/
 
boolean sendMessage(String username, String password, String body, String compression, String to){
    boolean flag = false;
    try{ 
        String hostName = "ipipi.com";
        to = to + "@sms.ipipi.com";
        Properties props = System.getProperties();
        props.put("mail.smtp.auth", "true");
        Session mailSession = Session.getDefaultInstance(props, null);
        Message msg = new MimeMessage(mailSession);
        msg.setFrom(new InternetAddress(from));
        InternetAddress[] address = {new InternetAddress(to)};
        msg.setRecipients(Message.RecipientType.TO, address);
        msg.setSubject(compression);
        msg.setText(body);
        msg.setSentDate(new Date());  
 
        transport = mailSession.getTransport("smtp");
        transport.connect(hostName, username, password);
        msg.saveChanges();
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close(); flag = true;
    }catch (Exception e) {
        e.printStackTrace();
        flag = false;
    }
    return flag;
}

This method takes as parameter your ipipi account information (username and password), the receiver phone number (it should include country code as well, for example +82101234567), the message itself.

The compression option is optional , check ipipi documentation for list of compression values (http://www.ipipi.com/help/helpsms.htm).

After initializing the value, we attempt to connect to ipipi and send the SMS message.

Comments

You must be logged in to post comments.