Send SMS via Twilio

By | 09/10/2014

While I was looking for a tool to send SMS text messages to my customers, I came across Twilio. It seemed pretty straightforward to integrate into my applications. So I decided to write a small script to test this service. This post describes some easy steps to get started with Twilio, more in particular, we write a small piece of Ruby code (and Python variant) that would send an SMS to an array of cell phone numbers.

Let’s get started

1) Go to www.twilio.com and sign up for a free account
2) Get yourself a free trial phone number
3) Note down your AccountSID and AuthToken as well as your phone number

Here is the little script. Call it sms.rb or similar and execute it using “ruby sms.rb command”. If all goes well, you will receive a text message from the Twilio phone number.

require 'rubygems'
require 'twilio-ruby'
 
account_sid = ""
auth_token = ""
client = Twilio::REST::Client.new account_sid, auth_token
 
from = "+14846624263" # Your Twilio number
 
friends = {
"+32473xxxxxx" => "Wim",
"+32485xxxxxx" => "Iris",
}
friends.each do |key, value|
  client.account.messages.create(
    :from => from,
    :to => key,
    :body => "Hey #{value}, how are you?"
  ) 
  puts "Sent message to #{value}"
end

This is the Python variant

from twilio.rest import TwilioRestClient
 
account_sid = "AC2b99feef2c2fcaad4bea74b969cfb35c"
auth_token = "dab2b9ce1d0b0f61e48982afce151552"

client = TwilioRestClient(account_sid, auth_token)

sms = client.sms.messages.create(body="All in the game",
    to="+32473xxxxxx5",   #Your phone number
    from_="+14846624263") #Your Twilio number

print sms.body