简体   繁体   中英

How to send SMS via Twilio in Rails?

I'm trying to create a simple rails app where user can send me a SMS via Twilio. A user just needs to fill in the form on the home page with his name, email, some text and submit it. I need to create a function that would grab those 3 pieces of information from params, create a text message and send it to my phone number, but I have no idea how to do that.

Those are the form and routes that I tried to create for this:

View: app/views/home/index.html.erb

    <div>
        <%= form_for @phone, url: 'home/send_text' do |f| %>
        <%= f.label :name %>
        <%= f.text_field :name %>
        <%= f.label :email %>
        <%= f.text_field :email %>
        <%= f.label :message %>
        <%= f.text_field :message %>
        <%= f.submit 'Submit', class: "btn btn-primary" %>
        <% end %>
    </div>

Routes:

Rails.application.routes.draw do
  root 'home#index'
  post 'home/send_text'
end

Just follow the below steps :-

Step 1 : Create and Configure Twilio Account

Step 2 : To integrate Twilio on Rails you have to add twilio-ruby gem to your Gemfile.

gem ‘twilio-ruby’

Step 3 : After bundle install you have to use below code

config/initializers/twilio.rb

require 'rubygems' 
require 'twilio-ruby'

module TwilioSms
  def self.send_text(phone, content) 
    # phone :- phone number to which you want to send sms 
    # content :- Message text which you want to send
    twilio_sid = "*****" # paste twilio sid
    twilio_token = "*****" # paste twilio token
    twilio_phone_number = "+1******" # paste twilio number
    begin
      @twilio_client = Twilio::REST::Client.new twilio_sid, twilio_token

      @twilio_client.api.account.messages.create(
      :from => twilio_phone_number,
      :to => phone, 
      :body=> content

      )
    rescue Twilio::REST::TwilioError => e
       return e.message
    end
    return "send"
  end
end

Step 4 : call this method from where you want to call either controller or model.

TwilioSms.send_text("+91*******", "Hello") 

that's it... :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM