学生向けプログラミング入門 | 無料

学生向けにプログラミングを無料で解説。Java、C++、Ruby、PHP、データベース、Ruby on Rails, Python, Django

Ruby on Rails | Gmail設定

↓↓クリックして頂けると励みになります。

Gメール設定
Gメール設定


Gmailを使ってメールの送信をできるようにします。
Ruby on RailsアプリケーションでGmailを使用してメール送信を設定するには、以下の手順を実行できます。
GmailのSMTPサーバーを使ってメールを送信することができます。


以下の手順でGmailのセキュリティを2段階認証プロセスに変更し、アプリパスワードを生成してください。
mrradiology.hatenablog.jp




1.記述の変更 config\environments\development.rb(35行目)
「false」を「true」に変更します。

config.action_mailer.raise_delivery_errors = true



2.記述の追加 config\environments\development.rb(67行目)
「user_name」はご自分のGmailアドレスを、「password」に生成したアプリパスワードを入力してください。

  #Gメールの設定
  config.action_mailer.delivery_method = :smtp

  config.action_mailer.smtp_settings = {
    address: "smtp.gmail.com",
    port: 587,
    enable_starttls_auto: true,
    authentication: "plain",
    user_name: 'win.rails.learn@gmail.com',
    password: '生成したアプリパスワード'
  }



1.記述変更 config\initializers\devise.rb(28行目)
ご自分のアドレスを入れて下さい。

config.mailer_sender = 'win.rails.learn@gmail.com'



2.記述変更 config\initializers\devise.rb(160行目)
tureをfalseに変更します。

config.reconfirmable = false



記述追加 app\models\user.rb(6行目)
「, :confirmable」の記述を追加。「,」を忘れないようにして下さい。

  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable,
         :confirmable



app\models\user.rb

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable,
         :confirmable

  validates :full_name, presence: true, length: {maximum: 50}
end



コマンド
rails g migration AddConfirmableToDevise


マイグレーションファイル更新
db\migrate\20200723081403_add_confirmable_to_devise.rb

class AddConfirmableToDevise < ActiveRecord::Migration[6.0]
  def change
    add_column :users, :confirmation_token, :string
    add_column :users, :confirmed_at, :datetime
    add_column :users, :confirmation_sent_at, :datetime

    add_index :users, :confirmation_token, unique: true    
  end
end



コマンド マイグレーション
rails db:migrate


Posticoでユーザテーブル確認

ユーザテーブル確認
ユーザテーブル確認



サーバ起動
rails s


ブラウザ確認
http://localhost:3000/


新規アカウント登録するとメールが送られてきます。
送られてきたメールからアカウント有効化をするとログインできるようになります。



以上の手順に従って、Ruby on RailsアプリケーションでGmailを使用してメール送信を設定できます。
ただし、セキュリティの観点から、パスワードやSMTP設定などの機密情報を適切に保護することが重要です。
また、本番環境ではセキュリティを強化するためにさらに対策を講じることが必要です。


↓↓クリックして頂けると励みになります。