Rails apps can send from multiple SMTP accounts

One of our Rails apps send both bulk email blasts, and also onesey-twosey non-bulk emails such as welcome emails or follow-up emails.

We wanted the non-bulk emails to actually come from one of our monitored customer service accounts, while still using Sendgrid for our bulk email blasts.

When we searched, we found a lot of schemes for configuring Rails to permit multiple SMTP accounts, however they seemed overly complex.

Here’s how we solved it very simply:

  • In addition to our existing usermailer.rb, we created a new nonbulk_mailer.rb.
  • We removed the ‘normal’ SMTP configuration from environment.rb
  • At the top of each of our xxxxmailer.rb class definition files we added self.smtpsettings = with the appropriate smtp configuration hash
  • We moved the ‘personal’ email handlers out of the original usermailer.rb and into nonbulk_mailer.rb (and moved the associated views as well)

So our mailer classes each look like:

class NonBulkMailer < ActionMailer::Base  
self.smtp_settings = {  
:address => ENV['MF_NONBULK_ADDRESS'],
:port => ENV['NONBULK_PORT'], 
:domain => ENV['NONBULK_DOMAIN'], 
:user_name => ENV['NONBULK_USER'], 
:password => ENV['NONBULK_PWD'] } ...

Note we keep the passwords etc in environment variables, so each environment (local, Heroku staging, Heroku production) can have their own settngs, plus all passwords are kept out of our git repository.