ひーろのアウトプットブログ

プログラミングの学習記録と開発日記です

ActionMailerでGmail宛にメールを送る際に発生したNet::SMTPAuthenticationErrorの解消

お問い合わせフォーム機能の作成でActionMailerを使用した。名前欄やメール欄を設けず、メッセージだけ記入して送信するシンプルな仕様で設計。
Railsガイドに沿って実装していったが、メッセージ送信時にNet::SMTPAuthenticationErrorというエラーが発生した。
調べたところGmail側の設定によるエラーだったようで、2段階認証のアプリパスワード設定の必要があった。
下記の方法で解消できた。

前提

ruby: 2.6.6
rails: 6.0.3.5

内容

config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
  port:                 587,
  address:              'smtp.gmail.com',
  domain:               'gmail.com',
  user_name:            '<ユーザー名>',
  password:             '<パスワード>',
  authentication:       'plain',
  enable_starttls_auto: true
}

config/environments/development.rbに自分のGmailアカウントへメールを送るための記述をする。

password: '<パスワード>',

このパスワードの入力が2段階認証で発行したアプリパスワードを入力する必要がある。

方法

googleアカウントへ行き、下記手順でアプリパスワードを発行する。
アカウント管理→セキュリティ→アプリパスワード→アプリとデバイス入力後、生成
16桁のアプリパスワードが発行されるので、先程のパスワード欄へ入力する。

環境変数

メールアドレスやパスワードをコードにそのまま記述するとセキュリティ上リスクが高いので、環境変数にいれて管理する。
環境変数の設定はターミナル上で行う。

$ vim ~/bash.profile

編集モードへ切り替え、メールアドレスとパスワードを入力する。

export EMAIL='************'
export APP_PASSWORD='*************' #発行したアプリパスワード

保存したらconfig/environments/development.rbに反映させる。

config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
  port:                 587,
  address:              'smtp.gmail.com',
  domain:               'gmail.com',
  user_name:            ENV['EMAIL'],
  password:             ENV['APP_PASSWORD'],
  authentication:       'plain',
  enable_starttls_auto: true
}

サーバーを再起動し問い合わせフォームからメッセージを送るとエラーが解消され、Gmailで受信できた。

参考

https://railsguides.jp/action_mailer_basics.html

https://qiita.com/aokabin/items/704fe30c33b885ac14f1

https://qiita.com/yuichir43705457/items/7cfcae6546876086b849