Saturday, November 12, 2016

IOT: Send SMS/MMS in Java using Twilio


Objective: The Objective of this exercise is to send an SMS/MMS in Java using Twilio.

GitHub Source:

What is Twilio?
Twilio is powering the future of business communications, enabling developers to embed voice, VoIP, and messaging into applications. They virtualize all infrastructure needed in a cloud-based, global environment, exposing it through the Twilio communications API platform. Applications are simple to build and scalable. Enjoy flexibility with pay-as-you go pricing, and benefit from cloud reliability.
Twilio Voice allows your applications to make and receive phone calls. Twilio SMS enables your applications to send and receive SMS messages. Twilio Client allows you to make VoIP calls from any phone, tablet, or browser and supports WebRTC. 
Steps:
1.  Sign up for free Twilio account from https://www.twilio.com/try-twilio. Once you have signed up, go to your console, get a new Twilio number and note the Account SID and Auth Token, which will be needed for the code sample below. Twilio Rest API’s in Java will be used in this example to send MMS. For more details, please refer the following links:
https://www.twilio.com/docs/
https://www.twilio.com/docs/api/rest/sending-messages#post
2.  Once the above connection is complete, Power ON the Raspberry Pi. Now connect to Raspberry Pi using Putty with your Raspberry Pi Credentials and by-default, you will in the path /home/pi. 
3.  For proper organization purpose, I created folders (using mkdir command) \projects. But this is not mandatory. You can even skip this step and move to next step.
mkdir projects
4.  From the \projects folder, execute the following command to Git clone the code to your local raspberry Pi.
git clone https://github.com/agilerules/IOT.git
5.  Once the git clone is complete, you will see IOT folder created in \projects folder. Now go to IOT folder (using the command cd IOT) and you will see the folder Twilio inside this folder IOT.
6.  Move to this Twilio\src\main\java\com\twilio\Twilio folder (using the command cd command) and run the following command to edit the TwilioMMS.java.
vi TwilioMMS.java
7.  Now modify the following lines to enter your Twilio Account SID and Auth Token (which is available in Twilio Console).
8.  Also edit the TO and From numbers , where TO should be the mobile number for which you want to send SMS and From is the Twilio number that was received during the registration process in Twilio Console.
params.add(new BasicNameValuePair("To", "<Mobile_No_for_which_you_want_to_send_SMS>"));
params.add(new BasicNameValuePair("From", "<Your_Twilio_Registered_Number>"));
9.  Save the file with Esc command+ :wq!
10. Now move back to Twilio folder and run the following commands to perform maven clean and maven package. (Incase if mvn command is not recognized then it means that maven is not installed on your Raspberry Pi.  Please follow my blog on how to install Maven on Raspberry Pi.
mvn clean
mvn package
11. Now execute the following command to start the maven build and run the Java class TwilioMMS.java in standalone mode. (Incase if mvn command is not recognized then it means that maven is not installed on your Raspberry Pi.  Please follow my blog on how to install Maven on Raspberry Pi.
mvn exec:java -Dexec.mainClass="com.twilio.Twilio.TwilioMMS" -Dexec.classpathScope=runtime
12. Now the program will send MMS to the phone number that is registered.
13. Here is the source code explanation below:
a) pom.xml
The below is the library dependency that we need for this application:
twilio-java-sdk – This is for Twilio Java SDK.
<dependencies>
            <!--  Twilio is required to SMS/MMS -->
            <dependency>
                  <groupId>com.twilio.sdk</groupId>
                  <artifactId>twilio-java-sdk</artifactId>
                  <version>6.3.0</version>
                  <scope>compile</scope>
         </dependency>
   </dependencies>
b) TwilioMMS.java
This java class has one method named sendMMS(), which will send MMS to mobile number that is provided as input in the Java program.
1.       Register TwilioRestClient with the ACCOUNT_SID and AUTH_TOKEN value. These values will be fetched from Twilio console.
// Find your Account Sid and Token at twilio.com/user/account
public static final String ACCOUNT_SID = "<Your_Twilo_Account_SID_Here>";
public static final String AUTH_TOKEN = "Your_Auth_Token_Here";
TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
2.       Build the required parameters to send to MMS by populating the List with instance of BasicNameValuePair().
a)      To is the number for which the SMS need to be send(i.e country code, followed by number. If US, it is +1 followed by number),
b)      From is the Twilio registered number (i.e country code, followed by number. If US, it is +1 followed by number)
c)       Body is the message that need to be send as MMS
d)      MediaURL is the image URL, which will be part of the MMS.
// Build the parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("To", "<Mobile_No_for_which_you_want_to_send_SMS>"));
params.add(new BasicNameValuePair("From", "<Your_Twilio_Registered_Number>"));
params.add(new BasicNameValuePair("Body", "This is test message and check the below URL:"));
params.add(new BasicNameValuePair("MediaUrl", mediaURL));
3.       Create instance of messageFactory and invoke create() method by passing the parameter List created in the above step. This will send the MMS to the mobile number mentioned it the TO parameter in the above step. The image URL mentioned in the MediaURL will be listed in the MMS. Since the Twilio trial account is used, the MMS will have the additional text saying “Sent from your Twilio trial account.”
MessageFactory messageFactory = client.getAccount().getMessageFactory();
         Message message;
            try {
System.out.println("About to send MMS using Twilio to the mobile number..");
                  message = messageFactory.create(params);
System.out.println("MMS is successfully send using Twilio and the SID of the message is: "+message.getSid());
            } catch (TwilioRestException e) {
System.out.println("Error while sending the SMS from Twilio..");
                  e.printStackTrace();
         }
  
4.       That’s the end of the tutorial. Hope it was useful.

1 comment:

  1. Your post is very interesting to read. Use MsgClub Bulk SMS API Java and send number of messages at a time.

    ReplyDelete