Last Updated: February 25, 2016
·
4.755K
· asanghi

Rails 4: Dynamic SMTP Settings

So in versions of Rails before Rails4, it was very convoluted and hard to set SMTP settings dynamically depending on input parameters.

The use case I had in mind was for a multi-tenant application which allows for your tenant to supply their own SMTP settings for emails generated for/on behalf of their account in your Rails app.

In Rails 4, this is way easier now.

class BusinessMailer < ActionMailer::Base
  def somemailer(biz,...)
    mail delivery_method_options: biz.smtp_settings,
         to: user.email,
         subject: "Some subject"
  end
end

You probably have more than one mailer action though, so thanks to the other awesome feature of Rails4 Mailers, you can now have callbacks so you could implement this once in your BusinessMailer mailer class

class BusinessMailer < ActionMailer::Base

  after_filter :set_smtp

  def somemailer(biz,user)
    @biz = biz
    mail to: user.email, subject: "Some subject"
  end

  def somemailer2(biz,user)
    @biz = biz
    mail to: user.email, subject: "Another subject"
  end

  private

  def set_smtp
    mail.delivery_method.settings.merge!(@biz.smtp_settings)
  end

end

Voila! All your mails within BusinessMailer will read smtp settings from @biz. You just need to ensure that @biz is set in your mailer action.

2 Responses
Add your response

You called afterfilter :setsmtp but your private method is named set_delivery_options

over 1 year ago ·

Thanks! Good catch. Updated. Private doesnt matter though

over 1 year ago ·