1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Rails]twilioでSMSを送信する

Posted at

tiwilioでサインアップする

https://jp.twilio.com/try-twilio
まずは会員登録をしましょう。
テストであれば無料で使えます。

必要な情報を入手

TRIAL NUMBERアカウントSIDAUTHTOKENを入手しましょう!
(consoleのトップ画面に表示されています。)

gemをインストール

gem 'twilio-ruby'

コード作成

モデルを作成

message.rb
class Message
  def initialize(tel:)
    @tel = tel
  end

  def hello(user:)
    @message = "#{user.name}さんこんにちは"
    send
  end

  private

  def send
    @tel = "+81" + @tel.slice(1..11)
    account_sid = ENV['TWILLIO_ACCOUNT_SID']
    auth_token = ENV['TWILLIO_AUTH_TOKEN']
    @client = Twilio::REST::Client.new account_sid, auth_token
    @client.messages.create(
        from: ENV['TWILLIO_PHONE_NUMBER'], # TRIAL NUMBERを入力
        to: @tel,
        body: @message
    )
  end
end

コントローラーを設定

users_controller.rb
def send_sms
    user = User.first
    message = Message.new(tel: ENV['YOUR_PHONE_NUMBER']) # twilioに登録した電話番号
    message.hello(user: user)
end

完成です!

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?