ruby-on-railsemailruby-on-rails-4actionmailer

Rails ActionMailer preview in production


I am using rails 4.1.1 and ActionMailer::Preview for previewing emails. In development environment everything is working excellent.

But in production environment the preview routes are not accessible. I store the previews in test/mailers/previews/

Is is possible to enable them for production?


Solution

  • In addition to this:

    config.action_mailer.show_previews = true
    

    you will also need to set

    config.consider_all_requests_local = true
    

    in your environment for the preview routes to be accessible. This has other implications as well (see https://stackoverflow.com/a/373135/1599045) so you likely don't want to enable this in production. However, if you have a custom environment that's not development, the combination of those two should get things working.

    EDITED TO ADD:

    The original question was for rails 4.1.1, which doesn't have config.action_mailer.show_previews available. To get ActionMailer previews working in non-development environments in rails 4.1.1, you need to first add some routes to config/routes.rb (in this case, my environment is named custom):

    if Rails.env.custom?
      get '/rails/mailers'               => "rails/mailers#index"
      get 'rails/mailers/download/*path' => "rails/mailers#download"
      get '/rails/mailers/*path'         => "rails/mailers#preview"
    end
    

    Then you need to autoload the libraries needed in your environment's config file (in my case, config/environments/custom.rb):

    config.action_mailer.preview_path ||= defined?(Rails.root) ? "#{Rails.root}/test/mailers/previews" : nil
    config.autoload_paths += [config.action_mailer.preview_path]
    

    This seems to perform the same task as config.action_mailer.show_previews does.

    As with 4.2, you will still need to adjust the local request configuration as above depending on whether your custom environment is being used locally or on a server.