A Micro Toolbox

ソフトウェアのニッチな問題の対処記録です

ダミーのSMTPサーバ

RailsのActionMailerを動作確認するのにGmailを使っていたけれど、もっと認証のゆるいSMTPサーバを想定した送信テストが必要になって、ダミーのSMTPサーバとして使えるものを調べた。

メール送信する環境はWindows 10 + Ruby 2.2 + Rails 4.2.6。
ダミーのSMTPサーバの条件は、SMTP AUTH PLAINが通って、日本語の件名と本文が確認しやすいこと。

結論から言うと、MailCatcherが楽だった。

Rails側の準備

config/environments/development.rb

  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    address: 'localhost',
    port: 25,
    domain: 'example.com',
    user_name: 'user',
    password: 'password',
    authentication: 'plain',
  }


app/mailers/application_mailer.rb

class ApplicationMailer < ActionMailer::Base
  layout 'mailer'
end


app/mailers/test_mailer.rb

class TestMailer < ApplicationMailer
  default from: "foo@example.com"

  def greet
    @greeting = "送信テストです\n届くといいですね。"

    mail(to: "bar@example.com", subject: "送信テスト")
  end

end


app/views/test_mailer/geet.text.erb

MAIL BODY -->
<%= @greeting %>
<-- MAIL BODY


送信テストはRailsのコンソールで行う。

> rails c
Loading development environment (Rails 4.2.6)
irb(main):001:0> TestMailer.greet.deliver_now

MailCatcher

DevKit設定済みの状態で、gem installでインストール。

> gem install mailcatcher

ポート番号を--smtp-portオプションで指定して起動。
指定しないと1025番が使われる。
何か問題があったときのために-vオプション(冗長表示)もつけておく。

> mailcatcher -v --smtp-port 25
Starting MailCatcher
==> smtp://127.0.0.1:25
==> http://127.0.0.1:1080

ブラウザでhttp://localhost:1080を開くとメールの確認画面になる。

config.action_mailer.smtp_settingsはaddressとportの指定だけあればよいが、user_name, passwordがあっても特に問題ない。

終了はCtrl+Cでできる。

Pythonワンライナー


Python 2.7 32bit版を入れていたので、ワンライナーでダミーSMTPサーバを起動してみた。

> python -m smtpd -n -c DebuggingServer localhost:25

このSMTPサーバにメール送信すると、ワンライナーで起動したコンソール(コマンドプロンプト)にメールが表示される。

ただし、BASE64エンコーディングされたままなので日本語としてはそのまま読めない。

config.action_mailer.smtp_settingsにuser_nameとpasswordを設定してテスト送信したら、AUTHには対応していない旨のエラーになった。

Net::SMTPAuthenticationError: 502 Error: command "AUTH" not implemented
<||