Aarish Ramesh
Aarish Ramesh

Reputation: 7023

Using SMPP to send sms texts in JAVA

I am trying to send sms using JAVA. After googling, I found out that SMPP protocol is to be used for it and stumbled upon the below source code.

public class SendSMS
{
public static void main(String[] args) throws Exception
{
    SendSMS obj = new SendSMS();
    SendSMS.sendTextMessage("<mobile number>");
}

private TimeFormatter tF = new AbsoluteTimeFormatter();

/*
 * This method is used to send SMS to for the given MSISDN
 */
public void sendTextMessage(String MSISDN)
{

    // bind param instance is created with parameters for binding with SMSC
    BindParameter bP = new BindParameter(
            BindType.BIND_TX, 
            "<user_name>",
            "<pass_word>", 
            "<SYSTEM_TYPE>", 
            TypeOfNumber.UNKNOWN,
            NumberingPlanIndicator.UNKNOWN,
            null);

    SMPPSession smppSession = null;

    try
    {
        // smpp session is created using the bindparam and the smsc ip address/port
        smppSession = new SMPPSession("<SMSC_IP_ADDRESS>", 7777, bP);
    }
    catch (IOException e1)
    {
        e1.printStackTrace();
    }

    // Sample TextMessage
    String message = "This is a Test Message";

    GeneralDataCoding dataCoding = new GeneralDataCoding(false, true,
            MessageClass.CLASS1, Alphabet.ALPHA_DEFAULT);

    ESMClass esmClass = new ESMClass();

    try
    {
        // submitShortMessage(..) method is parametrized with necessary
        // elements of SMPP submit_sm PDU to send a short message
        // the message length for short message is 140
        smppSession.submitShortMessage(
                "CMT",
                TypeOfNumber.NATIONAL,
                NumberingPlanIndicator.ISDN,
                "<MSISDN>",
                TypeOfNumber.NATIONAL, 
                NumberingPlanIndicator.ISDN, 
                MSISDN,
                esmClass, 
                (byte) 0, 
                (byte) 0, 
                tF.format(new Date()),
                null,
                new RegisteredDelivery(SMSCDeliveryReceipt.DEFAULT),
                (byte) 0,
                dataCoding, 
                (byte) 0, 
                message.getBytes());
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

}

But the problem I encounter with the source code is that it requires specific set of parameters like user_name, pass_word, system_type, SMSC IP address etc which I have no clue of. I have only recently known about the SMPP protocol and so am unaware of how to get this code working to fulfil my usecase of sending sms to my mobile. So can someone please help me get this code to work or guide me to a place where i can learn about doing this?

Upvotes: 4

Views: 32940

Answers (4)

Lokesh Bhoir
Lokesh Bhoir

Reputation: 21

Use following code for single class execution:

public class SmppTransport {

static Map sessionMap=new HashMap<String,String>(); 
String result=null;
public String send(String url, Map<String, String> map) throws Exception {
    int smscPort = Integer.parseInt(map.get("port"));
    String smscHost = map.get("send_url");
    String smscUsername = map.get("username");
    String smscPassword = map.get("password");
    String recipientPhoneNumber = map.get("phone_num");
    String messageText = map.get("text");

    try {
        SubmitSM request = new SubmitSM();
     // request.setSourceAddr(createAddress(senderPhoneNumber)); // you can skip this
        request.setDestAddr(createAddress(recipientPhoneNumber));
        request.setShortMessage(messageText);
     // request.setScheduleDeliveryTime(deliveryTime);           // you can skip this
        request.setReplaceIfPresentFlag((byte) 0);
        request.setEsmClass((byte) 0);
        request.setProtocolId((byte) 0);
        request.setPriorityFlag((byte) 0);
        request.setRegisteredDelivery((byte) 1); // we want delivery reports
        request.setDataCoding((byte) 0);
        request.setSmDefaultMsgId((byte) 0);

        Session session = getSession(smscHost, smscPort, smscUsername, smscPassword);
        SubmitSMResp response = session.submit(request);
        result=new String(response.toString());
    } catch (Exception e) {
        result=StackTraceToString(e);
    }
    return result;
}

private Session getSession(String smscHost, int smscPort, String smscUsername, String smscPassword) throws Exception{

    if(sessionMap.containsKey(smscUsername)) {
        return (Session) sessionMap.get(smscUsername);
    }

    BindRequest request = new BindTransmitter();
    request.setSystemId(smscUsername);
    request.setPassword(smscPassword);
    request.setSystemType("smpp");

 // request.setAddressRange(addressRange);
    request.setInterfaceVersion((byte) 0x34); // SMPP protocol version

    TCPIPConnection connection = new TCPIPConnection(smscHost, smscPort);
 // connection.setReceiveTimeout(BIND_TIMEOUT);
    Session session = new Session(connection);
    sessionMap.put(smscUsername, session.toString());

    BindResponse response = session.bind(request);
    return session;
}

private Address createAddress(String address) throws WrongLengthOfStringException {
    Address addressInst = new Address();
    addressInst.setTon((byte) 5); // national ton
    addressInst.setNpi((byte) 0); // numeric plan indicator
    addressInst.setAddress(address, Data.SM_ADDR_LEN);
    return addressInst;
}

public String StackTraceToString(Exception err) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    err.printStackTrace(pw);
    return sw.toString();
    }



public String sendSMS(String Port, String Host,String SMPPUserName,String SMPPPassword,String Phone_Number,String Message) throws Exception {
    String response=null;
    sessionMap.put("port",Port);
    sessionMap.put("send_url",Host);    
    sessionMap.put("username",SMPPUserName);
    sessionMap.put("password",SMPPPassword);
    sessionMap.put("phone_num",Phone_Number);
    sessionMap.put("text",Message);
    Set set=sessionMap.entrySet();//Converting to Set so that we can traverse  
    Iterator itr=set.iterator(); 
    while(itr.hasNext()){  

      Map.Entry entry=(Map.Entry)itr.next();  
           }  

    SmppTransport test =new SmppTransport();
    try {
        response=test.send("10.50.**.**", sessionMap);
        System.out.println(response);
    } catch (Exception e) {

        response=StackTraceToString(e);
    }
    return response;

}

public static void main(String[] args) throws Exception
{
    SmppTransport sm=new SmppTransport();
    String test=sm.sendSMS("80*6", "10.50.**.**", "f***obi", "x***fQ", "+9187965*****", "Testing1");
    System.out.println("Data: "+test);

}}

Upvotes: 2

gkiko
gkiko

Reputation: 2289

I've been working on SMPP project recently.

The library I used for SMPP protocol is OpenSMPP.

Here is the example of my class for building and sending SMPP data

public class SmppTransport implements Transport {

@Override
public void send(String url, Map<String, String> map) throws IOException {
    int smscPort = Integer.parseInt(map.get("port"));
    String smscHost = map.get("send_url");
    String smscUsername = map.get("username");
    String smscPassword = map.get("password");
    String recipientPhoneNumber = map.get("phone_num");
    String messageText = map.get("text");

    try {
        SubmitSM request = new SubmitSM();
     // request.setSourceAddr(createAddress(senderPhoneNumber)); // you can skip this
        request.setDestAddr(createAddress(recipientPhoneNumber));
        request.setShortMessage(messageText);
     // request.setScheduleDeliveryTime(deliveryTime);           // you can skip this
        request.setReplaceIfPresentFlag((byte) 0);
        request.setEsmClass((byte) 0);
        request.setProtocolId((byte) 0);
        request.setPriorityFlag((byte) 0);
        request.setRegisteredDelivery((byte) 1); // we want delivery reports
        request.setDataCoding((byte) 0);
        request.setSmDefaultMsgId((byte) 0);

        Session session = getSession(smscHost, smscPort, smscUsername, smscPassword);
        SubmitSMResp response = session.submit(request);
    } catch (Throwable e) {
        // error
    }
}

private Session getSession(String smscHost, int smscPort, String smscUsername, String smscPassword) throws Exception{
    if(sessionMap.containsKey(smscUsername)) {
        return sessionMap.get(smscUsername);
    }

    BindRequest request = new BindTransmitter();
    request.setSystemId(smscUsername);
    request.setPassword(smscPassword);
 // request.setSystemType(systemType);
 // request.setAddressRange(addressRange);
    request.setInterfaceVersion((byte) 0x34); // SMPP protocol version

    TCPIPConnection connection = new TCPIPConnection(smscHost, smscPort);
 // connection.setReceiveTimeout(BIND_TIMEOUT);
    Session session = new Session(connection);
    sessionMap.put(smscUsername, session);

    BindResponse response = session.bind(request);
    return session;
}

private Address createAddress(String address) throws WrongLengthOfStringException {
    Address addressInst = new Address();
    addressInst.setTon((byte) 5); // national ton
    addressInst.setNpi((byte) 0); // numeric plan indicator
    addressInst.setAddress(address, Data.SM_ADDR_LEN);
    return addressInst;
}

}

And my operator gave me this parameters for SMPP. There are many configuration options but these are essential

#host = 192.168.10.10 // operator smpp server ip
#port = 12345         // operator smpp server port
#smsc-username = "my_user" 
#smsc-password = "my_pass" 
#system-type = "" 
#source-addr-ton = 5
#source-addr-npi = 0

So if you want to test your code without registering with GSM service provider, you can simulate SMPP server on your computer. SMPPSim is a great project for testing. Download it and run on your computer. It can be configured in multiple ways e.g. request delivery reports from SMPP server, set sms fail ratio and e.t.c. I've tested SMPPSim on linux.

Upvotes: 6

skytreader
skytreader

Reputation: 11707

SMPP is a protocol between mobile network operators/carriers and content providers. The fields you specified (username, password, SMSC IP) are provisioned from the operators. Unfortunately, unless you work for a content provider company, or have a deal with an operator, you are unlikely to get these details.

Simulators can let you test out your SMPP code but they will not actually deliver content to your phone.

My best advice if you want to send SMS from your Java app would be to use an SMS API like Twilio's.

Upvotes: 0

Omar.Nassar
Omar.Nassar

Reputation: 379

Use this simulator here, It acts as a service provide, after build and test your application on it you have to change just config parameters(username, password, ip, port, ...) that provided to you by the service provider .

you can find all configurations to connect to this simulator in conf file.

Upvotes: 1

Related Questions