Railsでメールを送信する機能を実装する時はmailcatcherを使うと便利
Webアプリを作っていると、メールを送信する機能を作ることがよくあるかと思います。 そんな時はmailcatcherというgemを使うと、仮想SMTPのような形で使えるので便利です。
準備
Gemfileを更新して、 bundle install
します。
# Gemfile group :development do gem 'mailcatcher' end
設定ファイル記述
# config/environments/development.rb Rails.application.configure do ・ ・ ・ # 開発時のメール関連はMailCatcherを利用 # RAILS_ROOTでbundle exec mailcatcherを実行し、http://127.0.0.1:1080/でメールが確認できる config.action_mailer.default_url_options = { host: 'localhost:3000' } config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = { :address => "localhost", :port => 1025 } ・ ・ ・ end
送信されたメールを確認する
mailcatcherを起動します。
$ bundle exec mailcatcher Starting MailCatcher ==> smtp://127.0.0.1:1025 ==> http://127.0.0.1:1080
起動したら http://127.0.0.1:1080/
にアクセスすると、下のような画面が表示されます。
確認する
今回はconsoleからメールを送信して確認してみます。
# メール本文 mail = Mail.new do from 'test-from@example.net' to 'test-to@example.net' subject 'Test mail using mailcatcher' body 'There is a test mail.' end # SMTPの設定。ActionMailerに設定したのと同じもの。 mail.delivery_method :smtp, { :address => "localhost", :port => 1025 } # メール送信 mail.deliver!
http://127.0.0.1:1080/
にアクセスすると、メールが届いています。
あら便利。