LoginSignup
235
220

More than 3 years have passed since last update.

Rails の ActionMailer でメール送信処理

Last updated at Posted at 2017-01-28

やりたいこと

Rails で会員登録等の何らかのアクションが行われた際に、登録完了メールなど自動でメールが送られるようにする。

設定

まずは config の設定。使うのは Gmail だったのでそれ用の設定を書く。
他の記事では cofig/environments/○○.rb で書いているが、他の設定も書いていて見にくいので、今回は config/initializers/ 配下で設定する。

config/initializers/mail.rb
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
  address: 'smtp.gmail.com',
  domain: 'gmail.com',
  port: 587,
  user_name: 'Gmail のメールアドレス',
  password: 'Gmail のパスワード',
  authentication: 'plain',
  enable_starttls_auto: true
}

送信専用のアドレスを使う場合などは、 address を変更する。
また、違うドメインにしたければ domain を書き換える。

加えて、開発環境で試すたびに実際にメールが送られてくるのは超ウザいので
letter_opener を使って、開発環境でメールを送るとブラウザで別タブでメールが開くように設定。

group :development do
  gem "letter_opener"
end

Gemfile に付け足して bundle install
そして config/initializers/mail.rb を修正。

config/initializers/mail.rb
if Rails.env.production?
  ActionMailer::Base.delivery_method = :smtp
  ActionMailer::Base.smtp_settings = {
    address: 'smtp.gmail.com',
    domain: 'gmail.com',
    port: 587,
    user_name: 'Gmail のメールアドレス',
    password: 'Gmail のパスワード',
    authentication: 'plain',
    enable_starttls_auto: true
  }
elsif Rails.env.development?
  ActionMailer::Base.delivery_method = :letter_opener
else
  ActionMailer::Base.delivery_method = :test
end

次に下記コマンドを叩いてメーラーを作成する

rails g mailer NotificationMailer

実装

まずは先程作成したメーラーで、メール送信処理を作成。

app/mailers/notification_mailer.rb
class NotificationMailer < ActionMailer::Base
  default from: "hogehoge@example.com"

  def send_confirm_to_user(user)
    @user = user
    mail(
      subject: "会員登録が完了しました。", #メールのタイトル
      to: @user.email #宛先
    ) do |format|
      format.text
    end
  end
end

次はメール本文

app/views/notification_mailer/send_confirm_to_user.text.erb
<%= @user.name %> 様

○○への会員登録が完了しました。
マイページはこちら
<%= user_url(@user) %>

そして実際に処理を走らせるアクションにメール送信処理をさせる

app/controllers/users_controller.rb
class UsersController < ApplicationController
  before_action :set_user

  def create
    if @user.save
      NotificationMailer.send_confirm_to_user(@user).deliver
      redirect_to @user
    else
      render 'new'
    end
  end
end

これで create アクションが呼ばれると、メール送信処理も行われる。
ただ

NotificationMailer.send_confirm_to_user(@user).deliver

の処理が終わるまで、以降の処理がされないので ActiveJob 使いたい!なんて時は
deliverdeliver_later に変える。

NotificationMailer.send_confirm_to_user(@user).deliver_later

以上でメール送信処理ができる、、、はず。。

235
220
1

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
235
220