Using multiple domains on Action Mailer

My application is a multi-tenant application where each customer has your own domain.

That's a problem for Action Mailer because you need to set a specific domain like this:

config.action_mailer.default_url_options = { :host => "example.com" }

Looking for solutions for multiple domains, I find this one:

class ApplicationController < ActionController::Base
  before_filter :handle_action_mailer

  protected

  def handle_action_mailer
    ActionMailer::Base.default_url_options[:host] = request.host_with_port
  end
end

But it will not work if you use a queue to send emails like Resque or DelayedJob because the queues are processed in another thread.

In this case, you will need to use the customer host like that:

<p><%= link_to 'Update contact details', edit_contact_url(@contact, :host => @customer.host) %></p>

Note that this host attribute is a string column of my customers table:

class Notifier < ActionMailer::Base
  def contact(contact)
    @contact = contact
    @customer = contact.customer

    mail(:to => contact.email)
  end
end

That's all you need to use multiple domains on Action Mailer.

See ya!

blog comments powered by Disqus