プログラミングガール

Developing a better me

Vagrant開発環境でメールサーバを立てる

やりたいこと

普段Vagrant上でRuby on Railsのアプリを開発しています。
ユーザー認証にDeviseを使っていてサインアップの際、開発環境でアプリからメールを送りたい場面があったので、今回MailCatcherを使ってメールサーバをVagrant上に立てました。
※ 今回VagrantIPアドレス192.168.33.60としています。

MailCatcher

HOWTO

1.Gemをインストールする

※ アプリで使う他のGemと衝突する恐れがあるため、Gemfileには書かない。

$ gem install mailcatcher
2.以下をenvironment/development.rbに記述
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = { :address => "localhost", :port => 1025 }
config.action_mailer.default_url_options = { host: '192.168.33.60', port: 3000 }
3.MailCatcherを起動する
$ mailcatcher --http-ip 192.168.33.60
Starting MailCatcher
==> smtp://127.0.0.1:1025
==> http://192.168.33.60:1080
*** MailCatcher runs as a daemon by default. Go to the web interface to quit.
4.ブラウザからアクセスする

http://192.168.33.60:1080/

5.ルート画面からサインインし、メールが送られると、コンソールに以下の文言が表示される
Sent mail to programming_girl@hoge.com (10.1ms)
Date: Wed, 05 Oct 2016 09:56:34 +0900
From: please-change-me-at-config-initializers-devise@example.com
Reply-To: please-change-me-at-config-initializers-devise@example.com
To: programming_girl@hoge.com
Message-ID: <57f44fc21f0f5_1cfc3f81bcda37ac325df@develop.mail>
Subject: Confirmation instructions
Mime-Version: 1.0
Content-Type: text/html;
 charset=UTF-8
Content-Transfer-Encoding: 7bit

<p>Welcome programming_girl@hoge.com!</p>

<p>You can confirm your account email through the link below:</p>

<p><a href="http://192.168.33.60:3000/users/confirmation?confirmation_token=WPTMz1JQJm3gx4YxCfSt">Confirm my account</a></p>

Redirected to http://192.168.33.60:3000/
Completed 302 Found in 200ms (ActiveRecord: 12.4ms)
6.ブラウザ見るとこんなかんじ

本文に確認URLがあるので、Pushする。 f:id:hana_ori:20161005133543p:plain

あるいは5の文言中のconfirmリンクをブラウザで叩く
http://192.168.33.60:1080:3000//users/confirmation?confirmation_token=79y3We4KFXSMzExiEqsx

7.ログイン画面に遷移するので、ログインする