LoginSignup
1
1

More than 3 years have passed since last update.

最速 rails mail devise ウェルカムメール送信機能実装 action mailer不要 一番簡単

Last updated at Posted at 2020-06-04

【ゴール】

deviseユーザ登録時にmailerを使用してmailの送信(ウェルカムメール)
参考:https://web-camp.io/magazine/archives/19143
参考:https://freesworder.net/rails-mail/

【メリット】

■UXの向上
■アプリケーション完成度向上

【開発環境】

■ Mac OS catalina
■ Ruby on Rails (5.2.4.2)
■ Virtual Box:6.1
■ Vagrant: 2.2.7

【実装】

アプリケーションを作成

mac.terminal
$ rails new mail

$ cd mail

gemfile追加

app内.gemfile
gem 'devise' #deviseの会員登録時にメールを飛ばします
gem 'dotenv-rails' #環境変数に使用します。詳細は後述

ターミナルへ戻り諸々作成

mac.terminal
$ bundle install #gemfileをインストール

$ rials g devise:install #deviseを初期化

$ rails g devise User 

$ rails g devise:views

$ rails g devise:controllers users

DB,migrationfileを編集、下記のコメントアウ外す。

※メールの情報を追いかける為。

db/migrate/xxxxxxxxxx_devise_create_users.rb
# Confirmable
      t.string   :confirmation_token
      t.datetime :confirmed_at
      t.datetime :confirmation_sent_at
      t.string   :unconfirmed_email # Only if using reconfirmable

modelを編集

※「:confirmable」のアクセスも追加

user.rb
class User < ApplicationRecord
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable, :confirmable ←追加

end

.envファイルをルートディレクトリに追加し、下記を追記

※一応パスワードがあるので「.env」を導入、先のgemfile導入はこの為
※環境変数に埋め込passwordは事前に申請してください

/.env
mail = 'あなたのgamilアドレス'
password = 'パスワード申請が必要'

config/initializers/mail_config.rb作成、編集

※メールの形式を指定
※「user_name」「password」は上記の.envファイルから引っ張ってきています

config/initializers/mail_config.rb
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
  address: 'smtp.gmail.com',
  domain: 'gmail.com',
  port: 587,
  user_name: ENV['mail'],
  password: ENV['password'],
  authentication: 'plain',
  enable_starttls_auto: true
}

view/users/mailer/confirmation_instructions.html編集

confirmation_instructions.html

##任意に変更、メールの内容になります。

<p>Welcome <%= @email %>!</p>

<p>You can confirm your account email through the link below:</p>

##ここまで


<!-- <p><%#= link_to 'Confirm my account', confirmation_url(@resource, confirmation_token: @token) %></p> -->
#コメントアウト,今回不要の為

再度ターミナルへ

mac.terminal
$ rails db:migrate

$ rails s -b 0.0.0.0

以上でユーザー登録時にメール送信されているはずです。

action mailer等経由して3時間くらい時間取られましたが
思ったより簡単に実装できました。

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