MockSMTP (€8,99) and MailCatcher (open-source) are great tools when you’re trying to debug emails, but not everyone on your team necessarily has one of them installed (or maybe you just don’t have one of them running constantly).

In case you don’t know what MockSMTP and MailCatcher do: they’re essentially SMTP servers for development. Instead of sending emails to their intended recipients, they collect them and give you a nice UI where you can inspect them at your leisure.

Using MailCatcher or MockSMTP conditionally in development is actually pretty easy and only requires you to add a few lines of code to your development.rb file:

# encoding: UTF-8
require "net/smtp"

ThanksForAllTheFish::Application.configure do
  # … other settings redacted …

  # Try to sniff out if MockSMTP or MailCatcher is running
  begin
    smtp = Net::SMTP.start "localhost", 1025
    if smtp.started?
      smtp.quit
      puts ">> WARNING: Found an SMTP server on port 1025"
      puts " Assuming that it is MockSMTP or MailCatcher..."
      puts ">> Emails WILL be sent to the SMTP server on port 1025"


      config.action_mailer.delivery_method = :smtp
      ActionMailer::Base.smtp_settings = {
        address: "localhost",
        port: 1025
      }
    end
  rescue Errno::ECONNREFUSED
    puts ">> No SMTP server found on port 1025"
    puts ">> Emails will be sent to STDOUT"
  end

  # … other settings redacted …
end

What does this code do? First of all we require NET::SMTP so that we can use it to detect whether there is a server on port 1025 (luckily both MockSMTP and MailCatcher use port 1025 by default).

Secondly we try to start an SMTP connection to port 1025. If the connection starts, we know that there’s an SMTP server running there and thus we can configure Rails to use it to send emails. If the connection doesn’t start, we don’t need to do anything.

Port 1025 isn’t a standard port for SMTP, so there’s little danger that we’d end up sending real emails to people from our development machine. If someone has a live SMTP server running on a non-standard port on their development machine we can assume that they know what they’re doing and can deal with the consequences.