Search code examples
rubysinatraactionmailer

How can I use ActionMailer previews in a Sinatra app?


I have a Sinatra Ruby app with the ActionMailer gem for sending emails. The email sending functionality works fine, but I can't figure out how to use the preview functionality for development. My mailer mailer.rb is located in lib/companyname/mailers, and my preview mailer_preview.rb is located in spec/companyname/mailers/previews. When I run my app and navigate to http://localhost:26250/rails/mailers I get a 404 "Sinatra doesn't know this ditty" page.

What do I need to do to be able to see the previews in my browser?

mailer.rb

module CompanyName
  class Mailer < ActionMailer::Base
    def test_email(recipient_email_address)
      email = mail(to: recipient_email_address, from: "no-reply@companyname.com", subject: "Testing ActionMailer") do |format|
        format.html { "<h1>Testing</h1>" }
      end
      email.deliver_now
    end
  end
end

mailer_preview.rb

module CompanyName
  class MailerPreview < ActionMailer::Preview
    def test_email
      Mailer.test_email("test@email.com")
    end
  end
end

Solution

  • After looking at the code for ActionMailer I couldn't find any non-Rails method of configuration, so it looks like this isn't currently possible*. I ended up setting up a Sinatra endpoint to load the HTML from the MailerPreview class and just display it in the browser:

    mailers_controller.rb

    get "/emails/:email_name" do
      halt 404 unless ENV["ENABLE_MAIL_TEST_ENDPOINT"] == "true"
    
      email_preview = CompanyName::MailerPreview.public_send(params["email_name"])
      email_preview.html_part.decoded # Note: I switched to the Mail gem instead of ActionMailer, so the code may not be identical
    end
    

    *I am not a Rails expert so this may not be the case, however to the best of my abilities I could not see a solution.