Skip to content

Instantly share code, notes, and snippets.

@danker
Created June 28, 2015 00:11
Show Gist options
  • Save danker/75e269e13bb4ac487d51 to your computer and use it in GitHub Desktop.
Save danker/75e269e13bb4ac487d51 to your computer and use it in GitHub Desktop.
Groovy script to send an SMS via Twilio API
import org.apache.http.auth.AuthScope
import org.apache.http.auth.UsernamePasswordCredentials
import org.apache.http.client.CredentialsProvider
import org.apache.http.client.HttpClient
import org.apache.http.client.entity.UrlEncodedFormEntity
import org.apache.http.client.methods.CloseableHttpResponse
import org.apache.http.client.methods.HttpPost
import org.apache.http.impl.client.BasicCredentialsProvider
import org.apache.http.impl.client.HttpClientBuilder
import org.apache.http.message.BasicNameValuePair
@Grab(group='org.apache.httpcomponents', module='httpclient', version='4.5')
// Twilio Docs here:
// https://www.twilio.com/docs/api/rest/sending-messages#post
def accountSID = "INSERT_TWILIO_ACCOUNT_SID_HERE"
def authToken = "INSERT_TWILIO_AUTH_TOKEN_HERE"
def twilioURL = "https://api.twilio.com/2010-04-01/Accounts/"
def twilioMessagesEndpoint = "/Messages.json"
def provider = new BasicCredentialsProvider()
def credentials = new UsernamePasswordCredentials(accountSID, authToken)
provider.setCredentials(AuthScope.ANY, credentials)
def client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build()
def httpPost = new HttpPost(twilioURL + accountSID + twilioMessagesEndpoint)
def params = [
new BasicNameValuePair("To", "+15558675309"), // format numbers with: (+) (country code) (number)
new BasicNameValuePair("From", "+13146280315"), // format numbers with: (+) (country code) (number)
new BasicNameValuePair("Body", "Jenny, Jenny, who can I turn to?")]
httpPost.entity = new UrlEncodedFormEntity(params)
def response = client.execute httpPost
println("RESPONSE ->" + response)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment