How to render an email preview in Rails

I needed to render an email preview for users. Rails has an email preview system, but that's for development.

I needed to render an email preview for users. Rails has an email preview system, but that's for development.

Searching didn't turn up much. Except for the development options. So I dug into the code. Something I find myself doing more of.

There is an ActionMailer::Preview class. Turns out that's also for the development process. But there is a private method that does the work.

I pulled that code out and put into a controller.

...
  @email = UserMailer.invite_existing_letter_recipient(@letter, current_user)
  ActionMailer::Base.preview_interceptors.each do |interceptor|
    interceptor.previewing_email(@email)
  end
  @preview = @email.html_part.decoded
...

And in the view.

  <%= @preview.html_safe %>

Calling the interceptors does things like fix the inline images and inline the CSS. I'm using Inky. You might be using MJML. And those work by intercepting.

Lastly, I need to render it in an iFrame so the site styles don't interfere with the email.

Subscribe to WebDev news from candland.net

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe