How to Send an SMS With Ruby Using Twilio

September 07, 2016
Written by

how_to_send_sms_ruby

Here’s all the code you need to send an SMS with Ruby using Twilio:

require 'twilio-ruby'

client = Twilio::REST::Client.new(
  ENV['TWILIO_ACCOUNT_SID'],
  ENV['TWILIO_AUTH_TOKEN']
)

client.messages.create(
  from: "[YOUR TWILIO NUMBER]",
  to: "[YOUR CELL PHONE NUMBER]",
  body: "You just sent an SMS from Ruby!"
)

If you’d like a short explanation about how this works, check out this short video:

How About a Walkthrough?

The first thing we need for this to work is a Twilio account. Sign up for your free trial account here.

We also need an SMS-enabled phone number. You can search for and buy one in the Twilio console.

Sending an SMS using Twilio is as simple as making an HTTP POST request to the /Messages resource in the Twilio API. Twilio makes this super simple by providing a helper library. Let’s install the twilio-ruby gem from the terminal:

gem install twilio-ruby

Next, create a script called sms.rb and open it in your favorite text editor. At the top of the script file we’ll require the twilio-ruby gem:

require 'twilio-ruby'

Create a REST client object using the helper library. You can find the credentials you need for this step in the Twilio console. Store these in system environment variables for safe keeping.

client = Twilio::REST::Client.new(
  ENV['TWILIO_ACCOUNT_SID'],
  ENV['TWILIO_AUTH_TOKEN']
)

Use the client to send an SMS message from your Twilio number to your cell phone. Make sure to replace the phone number placeholders with your Twilio and cell phone numbers:

client.messages.create(
  from: "[YOUR TWILIO NUMBER]",
  to: "[YOUR CELL PHONE NUMBER]",
  body: "You just sent an SMS from Ruby!"
)

Head back to the terminal and run the script:

ruby sms.rb

In just a few seconds you should receive your text message!

Conclusion

If you’d like to learn more about using Twilio and Ruby together check out:

What are you building? I’d love to hear about it. You can reach me on Twitter @brentschooley or drop me an email at brent@twilio.com.