2
1

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】ActionMailerを用いたメール送信機能の実装

Last updated at Posted at 2020-04-25

#目標

ユーザーがログイン後に、Googleメールを送信する。

開発環境

・Ruby: 2.5.7
・Rails: 5.2.4
・Vagrant: 2.2.7
・VirtualBox: 6.1
・OS: macOS Catalina

前提

下記実装済み。

ログイン機能実装

#1.「development.rb」を編集

development.rb
Rails.application.configure do
  # 34行目を「true」に変更
  config.action_mailer.raise_delivery_errors = true
  .
  .
  .
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    port:                 587,
    address:              'smtp.gmail.com',
    domain:               'gmail.com',
    user_name:            'メールアドレス',
    password:             'パスワード',
    authentication:       'login',
    enable_starttls_auto: true
  }
end

#2.メーラーを作成

ターミナル
$ rails g mailer LoginMailer

#3.メーラーを編集

login_mailer.rb
class LoginMailer < ApplicationMailer
  def send_when_login(user)
    @user = user
    mail to: @user.email, subject: 'ログイン完了'
  end
end
プロパティ 役割
to 送信先の指定
cc 一斉送信先の指定
bcc 非表示送信先の指定
from メールの送信元名
subject メールタイトル
date メールの送信日時
reply_to 返信用アドレスの指定

#4.「send_when_login.html.erb」を作成し、編集

login_mailer/send_when_login.html.erb
<%= @user.name %><p>ログインが完了しました。</p>

#5.「application_controller.rb」を編集

application_controller..rb
# 追記
def after_sign_in_path_for(resource)
  LoginMailer.send_when_login(current_user).deliver
  root_path
end
2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?