Back to Blog
Integration Guides

How to Send SMS with Twilio and Ruby: Step-by-Step Tutorial

Use the Twilio Ruby gem to send SMS from Ruby and Rails applications with proper credential management and webhook handling.

DA
Danial A
Senior Twilio Consultant, Telphi Consulting
June 22, 2026
7 min read
Twilio
Integration
SDK
Mobile
How to Send SMS with Twilio and Ruby: Step-by-Step Tutorial

Twilio SMS and Ruby integrate through the official Twilio Ruby gem, which provides a Twilio::REST::Client class that you initialize with your Account SID and Auth Token to dispatch SMS using the client.messages.create method with a clean Ruby hash syntax. This integration is used by Ruby developers and Rails teams building web applications that need SMS for OTP delivery, system alerts, booking confirmations, or user notifications, and who want a well-documented gem that fits Ruby's idiomatic block and hash conventions without requiring manual REST request construction. The gem is installed with gem install twilio-ruby or added to a Gemfile, the client is instantiated with credentials from environment variables, and inbound SMS is handled by a Sinatra or Rails controller action that responds with TwiML generated by the twilio-ruby TwiML builder.

What You Need Before You Start

Install the Twilio Ruby gem by running gem install twilio-ruby in your terminal, or add gem 'twilio-ruby', '~> 7.0' to your Gemfile and run bundle install. Collect your Twilio Account SID, Auth Token, and a provisioned SMS-capable phone number. Store credentials in environment variables using the dotenv gem for local development by adding gem 'dotenv' to your Gemfile and creating a .env file at the project root with TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, and TWILIO_FROM_NUMBER defined, then calling Dotenv.load at the top of your Ruby script or in config/application.rb in Rails. For production, set environment variables through your hosting platform's dashboard or secrets manager rather than committing a .env file to version control. Add .env to .gitignore immediately after creating it to prevent accidental credential exposure.

Step-by-Step Integration Guide

In your Ruby script or Rails service class, require 'twilio-ruby' and construct the client with @client = Twilio::REST::Client.new(ENV['TWILIO_ACCOUNT_SID'], ENV['TWILIO_AUTH_TOKEN']). Send an SMS by calling message = @client.messages.create(from: ENV['TWILIO_FROM_NUMBER'], to: '+1xxxxxxxxxx', body: 'Your message text'), which returns a message object with message.sid and message.status attributes. Wrap the create call in a begin/rescue block rescuing Twilio::REST::RestError, logging the exception error.message and error.code, and re-raising or returning a structured error hash to the caller. For Rails applications, create a TwilioSmsService class in app/services that encapsulates the client initialization in an initializer and exposes a send_sms(to:, body:) method that the controller or job calls, keeping Twilio-specific logic outside the controller. For inbound SMS webhooks in Rails, add a route to config/routes.rb pointing to a controller action, and in the action construct a Twilio::TwiML::MessagingResponse, call response.message body: 'Your reply here', render xml: response.to_s, and set the content type to text/xml.

Common Issues and How to Fix Them

The Twilio client raises a Twilio::REST::AuthenticationError when ENV['TWILIO_ACCOUNT_SID'] or ENV['TWILIO_AUTH_TOKEN'] returns nil, which happens when the .env file is present but Dotenv.load has not been called before the client is instantiated, or the Rails application is running in an environment where dotenv is not loaded in the group. Add Dotenv.load or Dotenv::Rails.load to the earliest possible point in your application boot sequence, and add a validation in the TwilioSmsService initializer that raises an ArgumentError with a descriptive message if either credential is nil or empty. The create call raises Twilio::REST::RestError with error code 21614 when the destination number is not a valid mobile number, which surfaces when testing with landline numbers. Add a rescue for this specific error code in your service and return a user-facing message such as 'The provided number cannot receive SMS messages. Please use a mobile number.' rather than surfacing a raw API error. Rails CSRF protection causes Twilio's webhook POST to fail with ActionController::InvalidAuthenticityToken because Twilio does not send a CSRF token. Add protect_from_forgery with: :null_session or skip_before_action :verify_authenticity_token only on the inbound SMS controller action, and use Twilio webhook signature validation as the security mechanism instead.

How to Get More from This Integration

Build a Ruby SMS notification module that reads message templates from a YAML file in config/twilio_templates.yml with keys like otp_message, appointment_reminder, and order_confirmed containing template strings with ERB-style placeholders, then interpolates values at send time using Ruby's String % operator or ERB.new(template).result(binding), centralizing all message copy and making it editable without code changes. Add Active Job async SMS sending in Rails by creating a SendSmsJob that calls the TwilioSmsService in the perform method, and calling SendSmsJob.perform_later(to: phone, body: message) from controllers and models, which queues the SMS dispatch to Sidekiq or another backend so the HTTP response returns immediately without waiting for the Twilio API call. Implement signature validation for inbound webhooks by adding a before_action in the SMS controller that uses Twilio::Security::RequestValidator.new(ENV['TWILIO_AUTH_TOKEN']).validate(request.url, request.POST, request.headers['X-Twilio-Signature']), returning HTTP 403 for invalid signatures to reject spoofed webhook attempts.

Conclusion

Ruby and Twilio together provide an expressive, gem-based SMS integration that fits naturally into Rails applications and standalone Ruby services. Reach out to Telphi Consulting to implement and configure Twilio SMS in your Ruby or Rails application.

Share this article:
0 views

Ready to Transform Your Business Communications?

Get a free consultation with our VoIP experts and discover how we can help you save costs, improve efficiency, and scale your business.

Comments (0)

Join the discussion and share your thoughts (AI-moderated for quality)

Protected by AI moderation

Be the first to comment

No comments yet. Share your thoughts below.