Posted about 11 years ago. Visible to the public. Repeats.

Configuring ActionMailer host and protocol for URL generation

When you generate a URL in a mailer view, ActionMailer will raise an error unless you previously configured it which hostname to use. Configuring the correct hostname is quite annoying when you have multiple deployment targets with different hostnames, e.g. a staging server and a production server.

Dynamic solution when mail is delivered from request cycle

Using the hack below you don't need to configure a default hostname for your mailers. They will always use the hostname for the current request:

Copy
class ApplicationController < ActionController::Base before_action :make_action_mailer_use_request_host_and_protocol private def make_action_mailer_use_request_host_and_protocol ActionMailer::Base.default_url_options[:protocol] = request.protocol ActionMailer::Base.default_url_options[:host] = request.host_with_port end end

If your application server talks only HTTP and relies on the web server for SSL, and if the web server is setting a special HTTPS forwarding header, Rails recognizes that a request originally was on HTTPS and will return the correct protocol.

Hardcoded alternative for request-less deliveries

When you are sending mails from outside the request cycle, e.g. from a Cronjob or ActiveJob, the above does not help. There is no request context when asynchronously delivering mails.

You need to set the host statically in the respective environment files:

Copy
# config/environments/production.rb config.action_mailer.default_url_options = { host: 'www.example.com', protocol: 'https://' } # config/environments/staging.rb config.action_mailer.default_url_options = { host: 'staging.example.com', protocol: 'https://' } # config/application.rb as fallback/default config.action_mailer.default_url_options = { host: 'localhost', protocol: 'http://' }

After you configure ActionMailer defaults like this, you no longer need the before_filter above.

Your development team has a full backlog of feature requests, chores and refactoring coupled with deadlines? We are familiar with that. With our "DevOps as a Service" offering, we support developer teams with infrastructure and operations expertise.

Owner of this card:

Avatar
Henning Koch
Last edit:
7 months ago
by Henning Koch
Keywords:
route, routing, router
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more