2
2

More than 3 years have passed since last update.

新規登録時、ActionMailerでメール送信機能

Posted at

概要

ActionMailerを使って新規登録時にwelcomeメールを送ります。

前提

deviseを用いての、ログイン機能の実装。

導入手順

1. ActionMailerを利用する設定

welcomeメールの送信元はGmailを使う記載方法。
config/environments/development.rbにてActionMailerの設定方法の記述。

development.rb
Rails.application.configure do

#---中略---#

 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:       :plain,
    enable_starttls_auto: true
  }

アプリパスワードは2段階認証を設定の上16桁のパスワードを発行し、アプリパスワードに記載する。
以下、参考にさせていただきました。
Google メールアプリケーション用のパスワードを取得する
Google 二段階認証設定をONにする方法

2. Mailerクラス作成

$ rails g mailer UserNotice

3. Mailerクラス編集

app/mailers/user_notice_mailer.rb
class UserNoticeMailer < ApplicationMailer
  def send_signup_email(user)
    @user = user
    mail to: @user.email, subject: "会員登録が完了しました。"
  end
end

4. メール本文作成

app/views/user_notice_mailer/send_signup_email.text.erb
ようこそ <%= @user.name %> 様

この度はアカウント登録頂きましてありがとうございます。

5. Userモデル編集

app/models/user.rb
#---追加---#

  after_create :send_welcome_mail

  def send_welcome_mail
    UserNoticeMailer.send_signup_email(self).deliver
  end

after_create を使うことで、Userが新規作成された後にメールを送信するためのメソッドを呼び出すことができます。

以上で、welcomeメールが送信されるはずです。

2
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
2
2