7
3

More than 1 year has passed since last update.

本番環境でActionMailerを動かす 【Rails Heroku Gmail】

Last updated at Posted at 2022-09-09

環境

  • Ruby3系
  • Rails6系
  • Heroku
  • Gmail

実現したいこと

  • ActionMailerを使って本番環境でパスワードリセットメールを送信できるようにしたい。

現状

  • 本番環境でメール送信できない。(ActionMailerがうまく動かない)
  • 開発環境ではうまく動いている。(letter oppner webで確認した。)
  • エラーがいくつか発生した。Rails Missing host to link to!Net::SMTPAuthenticationError (535-5.7.8 Username and Password not accepted. Learn more at)**といったエラー。

解決策

一言で言うとdevelpment.rbの編集とGmailの設定をしないといけない。
これをやっていなかったのでうまくいかなかった。

Gmailの設定

Gmail側の設定については以下の記事が参考になった。
https://skillhub.jp/courses/137/lessons/977
development.rbの記述についても説明があったが、個人的に分かりにくい点があったので下で補足しています。

development.rb(herokuの場合)

以下はproduction.rb

config.action_mailer.default_url_options = { protocol: 'https', host:'アプリのURL'}
#ホストの設定

config.action_mailer.delivery_method = :smtp
#smtpを使う

config.action_mailer.smtp_settings = {
    port: 587,
    address:"smtp.gmail.com",
    domain: 'gmail.com', #Gmailを使う場合
    user_name: ENV['GMAIL_ADDRESS'], #Gmailアカウントのメールアドレス
    password: ENV['GMAIL_PASSWORD'], #Gmailで設定したアプリパスワード
    authentication: :plain,
    enable_starttls_auto: true
  }

config.action_mailer.default_url_options

ここの書き方は以下のようになる。

config.action_mailer.default_url_options = { protocol: 'https', host:'アプリのURL'}

user_name: , password: の箇所は環境変数を使うべき

セキュリティからして危ないので。環境変数を使わないとエラーにつながったというケースもある。(https://qiita.com/kobayashimakoto/items/c7a96ea9f6cbc8d2da77)

password: の箇所はGmailで設定したアプリパスワードを使う

Gmailアカウントのログイン時のパスワードではないので要注意。

参考にした記事

メールの設定

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