はじめに
開発環境である程度アプリケーションを作り、それをいざ本番環境で作るとなったとき、エラーになりうまく動かなかった。そこでherokuで正常に動作できるよう改善していく。
前提
デプロイしたところから開始する。
No | 項目 | 内容 |
---|---|---|
1 | OS | Mac |
2 | Ruby | 2.6.3 |
3 | rails | 6.0.4 |
4 | heroku | Heroku-20 |
heroku の状況確認
herokuコマンドで原因を探る。
ターミナル
$ heroku logs
▼エラーに対して、下記の記事を参考に解決していく。
本番環境の設定
本番環境の設定を見直す。
production.rb
...
config.action_mailer.perform_caching = false
config.action_mailer.raise_delivery_errors = true
host = 'https://toushitsutown.herokuapp.com'
config.action_mailer.default_url_options = { host: host }
config.action_mailer.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
:port => 587,
:address => 'smtp.gmail.com',
:user_name => ENV['GMAIL_USER'],
:password => ENV['GMAIL_PASS'], # Googleが発行する、16桁のアプリケーションパスワード
:domain => 'gmail.com',
:authentication => :plain,
:enable_starttls_auto => true
}
...
環境設定をターミナルで行う。
ターミナル
heroku config:set GMAIL_USER='使用するemail'
heroku config:set GMAIL_PASS='上記メールのpassword'
ちなみに、開発環境の場合
▼開発環境の設定
development.rbに、本番環境同様のsmtp_settingを記載する。
development.rb
...
config.action_mailer.asset_host = 'http://localhost:3000'
config.action_mailer.perform_caching = false
config.action_mailer.raise_delivery_errors = true
host = 'localhost:3000'
config.action_mailer.default_url_options = { host: host, protocol: 'http' }
config.action_mailer.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
:port => 587,
:address => 'smtp.gmail.com',
:user_name => ENV['GMAIL_USER'],
:password => ENV['GMAIL_PASS'], # Googleが発行する、16桁のアプリケーションパスワード
:domain => 'gmail.com',
:authentication => :plain,
:enable_starttls_auto => true
}
...
次に、環境変数を設定する。
~/.zshrcに記載する。bashを使用している場合は~/.bash_profileに記載する。
~/.zshrc
# 環境変数
export GMAIL_USER='使用するemail'
export GMAIL_PASS='上記メールのpassword' # アプリパスワード
おわりに
これで環境設定が完了した。
参考
▼Action Mailerでメール送信機能を作る