Skip to content

Navigation Menu

Sign up

How To: Send emails from subdomains

obie edited this page Feb 21, 2011 · 8 revisions

Devise sends registration confirmations, forgotten password messages, and other email messages. These will originate from the main domain by default, but you can modify the application so these emails originate from subdomains.

Add the following code to the file app/helpers/url_helper.rb:

def set_mailer_url_options
 ActionMailer::Base.default_url_options[:host] = with_subdomain(request.subdomain)
end

and modify the file app/controllers/application_controller.rb to add:
include UrlHelper
before_filter :set_mailer_url_options

This information is provided from http://github.com/fortuity/rails3-subdomain-devise/blob/master/TUTORIAL.textile and Thanks to Tom Howlett for this contribution.

Alternate Method

The solution detailed above doesn’t work for setting arbitrary subdomains and is a problem if you’re triggering generation of email during a request in one subdomain (or the root domain of your application) and want the links in the email to reference a different subdomain. One of the approaches to making that work is to give the url_for helper a :subdomain option.

# app/helpers/subdomain_helper.rb
module SubdomainHelper
 def with_subdomain(subdomain)
 subdomain = (subdomain || "")
 subdomain += "." unless subdomain.empty?
 host = Rails.application.config.action_mailer.default_url_options[:host]
 [subdomain, host].join
 end
 
 def url_for(options = nil)
 if options.kind_of?(Hash) && options.has_key?(:subdomain)
 options[:host] = with_subdomain(options.delete(:subdomain))
 end
 super
 end
end

The next step is crucial. Make sure that Devise mixes in your new subdomain helper in config/application.rb

 config.to_prepare do
 Devise::Mailer.class_eval do 
 helper :subdomain 
 end
 end

Now when you do a link_to in your Devise mailer template, you can specify a :subdomain option.

link_to 'Click here to finish setting up your account on RightBonus',
 confirmation_url(@resource, :confirmation_token => @resource.confirmation_token, :subdomain => @resource.subdomain)

This alternate method is provided by Obie Fernandez

Clone this wiki locally

AltStyle によって変換されたページ (->オリジナル) /