当前位置: 首页 > 知识库问答 >
问题:

如何在Rails中通过Twilio发送短信?

万俟修诚
2023-03-14

查看: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>

路线:

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

共有1个答案

西门淮晨
2023-03-14

只需按照以下步骤操作:-

步骤1:创建和配置Twilio帐户

步骤2:要在Rails上集成Twilio,必须将twilio-ruby gem添加到Gemfile中。

gem ‘twilio-ruby’
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
TwilioSms.send_text("+91*******", "Hello") 
 类似资料: