It’s now or never

IT系の技術ブログです。気になったこと、勉強したことを備忘録的にまとめて行きます。

初めてのRuby On Rails③ (メールを送る)

Railsには、メールを送信するための仕組みとしてActionMailerという機能があります。
今回は、ActionMailerを使用して、Gmailのメール送信を試してみます。

1.環境設定

設定ファイルにGmailの設定を記入します。

config/environments/development.rb

  config.action_mailer.default_url_options = { :host => "localhost", :port => 3000 }
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    :address => "smtp.gmail.com",
    :port => 587,
    :domain => 'example.com',
    :user_name => "[ユーザー名]",
    :password => "[Gmailのパスワード]",
    :authentication => 'plain',
    :enable_starttls_auto => true,
  }

2.ActionMailerクラスを作成

ActionMailerクラスを生成するには、以下のコマンドを使用します。

rails generate mailer [Mialerクラス名] [アクション名]

例えば、messageというクラスにtestアクションを定義した場合は、
次のようにコマンドを実行します。

rails generate mailer message test

自動的に以下のファイルが生成されます。

create  app/mailers/message.rb
invoke  erb
create    app/views/message
create    app/views/message/test.text.erb
create    app/views/message/test.html.erb
invoke  test_unit
create    test/mailers/message_test.rb
create    test/mailers/previews/message_preview.rb

ActionMailerクラスは、app/mailers/配下に作成されています。

app/mailers/message.rb

class Message < ActionMailer::Base
  # デフォルトの送信もとアドレス
  default from: "[送信もとアドレス]"

  # Subject can be set in your I18n file at config/locales/en.yml
  # with the following lookup:
  #
  #   en.message.hellp.subject
  #
  def hellp
    @greeting = "Hi"

    mail to: "[送信先アドレス]"
  end
end

送信されるメッセージの本文は、
app/views/message/test.html.erbに定義します。

<h1>Message#test</h1>

<p>
  <%= @greeting %>, find me in app/views/message/test.html.erb
</p>

3. 送信確認

railsのコンソールからメールを送信してみます。

rails console

Message.test.deliver

app/mailers/message.rbに定義した、
送信先のメールアドレスにメールが送信されていれば、正常に動作しています。