2
8

More than 3 years have passed since last update.

[Ruby on rails] グループ作成機能⑥ Action mailerの環境変数化 gem(dotenv-rails) /.env

Last updated at Posted at 2021-08-03

環境変数を設定する

グループ作成機能⑤でグループメンバーにメールを送信する機能を実装しました。
gmailのアドレス、パスワードを直打ちしてるので、セキュリティ的にあまりよろしくありません。
そこで使うのが環境変数です。

なんか大変そう・・・:frowning2:と思ってたのですが、すぐ出来ます!!!

もうメールの機能は出来上がってる前提です。
メール機能の実装については⑤の記事をご確認ください。

gemのインストール

Gemfile
# 環境変数化のためのgem
gem 'dotenv-rails

そしたらbundle installで取り込みます。

.envファイル作成

Gemfileなどが置いてあるルートディレクトリに .env というファイルを作成します。
以下のような感じになるはずです!

スクリーンショット 2021-08-03 21.17.30.png

.envファイル記述

.env
KEY='ki.abcdfgh@gmail.com'    gmailのアドレス
SECRET_KEY='abcdefsgsdhsgjd'  ←アプリパスワード

.gitignoreに書き、pushされないようにする

.gitignore
#環境変数化で作成したファイル
/.env

これで、大事な情報の入ってる.envはgithubにプッシュされません。

config/enviroment.rbを書き換える

config/enviroment.rb
 config.file_watcher = ActiveSupport::EventedFileUpdateChecker
  config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
  config.action_mailer.raise_delivery_errors = true
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
      :user_name => ENV['KEY'],
      :password => ENV['SECRET_KEY'],
      :domain => "gmail.com",
      :address => "smtp.gmail.com",
      :port => 587,
      :authentication => :plain,
      :enable_starttls_auto => true
  }
end

以上のように環境変数を入れました。

mailers/application_mailer.rb
class ApplicationMailer < ActionMailer::Base
  default from: ENV["KEY"]
  layout 'mailer'
end

ここもメールアドレスを直打ちしてたので、環境変数に書き換えました。

以上で、⑤で作成したメール機能の環境変数化は完了です。

参考にさせていただいた記事

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