Previewing Emails in Rails Applications With the Mail_View Gem

Sending an email from an application through a development or staging environment can be cumbersome especially when you want to preview the mail before you hit the send button. With the gem ‘mail_view, you can easily preview emails right from your development environment. Previewing mail is important to ensure that you are sending the right email and to the right person. Never send a mail in dark anymore with the ‘mail_view gem! Check out more below on how it can be implemented in your application during the development stage. Rails Email Preview helps us to quickly view the email in web browser in development mode. 1. Add “gem ‘rails_email_preview’, ‘~> 0.2.29’ “ to gem file and bundle install. 2. Run “rails g rails_email_preview:install” this creates initializer in config folder and add routes. 3. Run “rails g rails_email_preview:update_previews” this crates mailer_previews folder in app directory. Generator will add a stub to each of your emails, then u populate the stub with mock data. Ex:
class UserMailerPreview def invitation UserMailer.invitation mock_user(‘Alice’), mock_user(‘Bob’) end def welcome UserMailer.welcome mock_user end private def mock_user(name = ‘Bill Gates’) fake_id User.new(name: name, email: “user#{rand 100}@test.com”) end def fake_id(obj) obj.define_singleton_method(:id) { 123 + rand(100) } obj end end
4. Parameters in search query will be available as an instance variable to preview class. Ex: if we have a URL like “/emails/user_mailer_preview-welcome?user_id=1” @user_id is defined in welcome method of UserMailerPreview it helps us to send mail to specific user.
class UserMailerPreview def welcome user = @user_id ? User.find(@user_id) : mock_user UserMailer.welcome(user) end end
5. To access REP url’s like this
rails_email_preview.rep_root_url rails_email_preview.rep_emails_url rails_email_preview.rep_email_url(‘user_mailer-welcome’)
6. We can send emails via REP, this will use environment mailer settings. Uncomment this line in the initializer to disable sending mail in test environment.
config.enable_send_email = false
References : 1. https://github.com/glebm/rails_email_preview 2. https://richonrails.com/articles/action-mailer-previews-in-ruby-on-rails-4-1 Looking to get your app developed? RailsCarma can help! Check out our portfolio to understand how we are helping to change the shape of software industry by providing Ruby on Rails Developer. Get in touch with us now!

Subscribe For Latest Updates

Related Posts

About Post Author

Leave a Comment

Your email address will not be published. Required fields are marked *