Customizing ActionMailer Preview header

1.7k Views Asked by At

I'd like to add some metadata to the header of my action mailer preview pages. I thought the easiest way would be to override this file somewhere in my project: https://github.com/rails/rails/blob/4-2-stable/railties/lib/rails/templates/rails/mailers/email.html.erb

Seeing as other things can be overridden in the lib/templates folder I thought something similar could work. I've tried the following without luck:

  • lib\templates\rails\mailers\email.html.erb
  • lib\templates\mailers\email.html.erb
  • lib\rails\templates\rails\mailers\email.html.erb

Is it possible to override this file somehow, and if so where?

Screenshot of where I want the metadata

2

There are 2 best solutions below

0
On BEST ANSWER

Ok, so I got this working in the end. Not sure if it's the best solution but it works.

First I copied email.html.erb mentioned in the question and placed it in test/mailers/previews. Then I made the customizations I needed to it and renamed it to email_preview_heading.html.erb.

Next I created a new initializer with an override of the MailersController. I placed the whole preview method from the original code inside, it can be found here: https://github.com/rails/rails/blob/4-2-stable/railties/lib/rails/mailers_controller.rb

The only change I made in the initializer was on row 35 as per below, that lines tells the preview controller which layout to use. The rest of the method was kept as before.

#config/initializers/email_preview_controller_override.rb
if Rails.env.development?
  class ::Rails::MailersController
    def preview
      ...
      render file: Rails.root.join('test/mailers/previews/email_preview_heading')
      ...
    end
  end
end

In the layout file I'm showing metadata passed as headers to the email which means I can access them like this: @email.header['description']

Make sure to only pass the headers when in preview mode though.

0
On

I was able to override email.html.erb by adding a view_path in an initializer:

# config/initializers/email_preview_controller_override.rb    

if Rails.env.development?
  module OverrideMailerController
    def self.prepended(base)
      base.prepend_view_path Rails.root.join('test', 'mailers','previews')
    end
  end
      
  ::Rails::MailersController.prepend OverrideMailerController
end  

Then I copied email.html.erb to /test/mailers/previews/rails/mailers. Works with Rails 5.2.3

In Rails 6, it's necessary to to wrap it in Rails.configuration.to_prepare do to avoid a DeprecationException as described here, like this:

if Rails.env.development?
  Rails.configuration.to_prepare do
    module OverrideMailerController
      def self.prepended(base)
        base.prepend_view_path Rails.root.join('test', 'mailers','previews')
      end
    end

    ::Rails::MailersController.prepend OverrideMailerController
  end
end