how to send sms from java code

Some code about how to use twiliofaces doer Sender inside java classes.

Add a accounts.properties in the classpath of the application - WEB-INF/classes path:

twilio.accounts=default,primo
# default account
account.default.twilioSid=1111
account.default.twilioToken=222
account.default.twilioNumber=333
account.default.applicationSid=444
#primo account
account.primo.twilioSid=5555
account.primo.twilioToken=666
account.primo.twilioNumber=777
account.primo.applicationSid=888

And inside the class where you want call some number:

  • Inject org.twiliofaces.cdi.doers.Sender (if you don’t specify the account name using the @TwilioAccount annotation, the container will inject the default account)

@Inject
@TwilioAccount(accountName = "default")
Sender sender1;

@Inject
@TwilioAccount(accountName = "primo")
Sender sender2;


public void directSmsSend(String to, String body) {

	try {
		// from the default account number
  		String sid1 = sender1.setTo(to).setBody(body).send();
		System.out.println("sms id: " + sid1);

		// from the primo account number
		String sid2 = sender2.setTo(to).setBody(body).send();
		System.out.println("sms id: " + sid2);
	} catch (TwilioRestException e) {
		e.printStackTrace();
	}


}
  • you can create your runtime org.twiliofaces.cdi.doers.simple.SimpleSender using:

public void smsSend(String accountSid, String authToken, String from, String to, String text, String mediaLink) {

	try {
  		String sid = new SimpleSender()
  				.accountSid(accountSid).authToken(authToken)
  				.from(from).to(to)
               			.body(text)
               			.media(mediaLink)
               			.send();
		System.out.println("sms id: " + sid);
	} catch (TwilioRestException e) {
		e.printStackTrace();
	}


}
comments powered by Disqus

Contact

Do you want collaborate with us?
Do you like this project?
Questions?
Please send me an email!

fiorenzo.pizza@gmail.com

Github code

Fork the twiliofaces repository on GitHub
and clone it to your local PC.

Get Started

Copy the Twiliofaces JAR file into your /WEB-INF/lib directory, or include all required Maven dependencies in your pom.xml!