June 12, 2023
•Last updated November 5, 2023
Using the letter_opener Gem with Ruby on Rails | Rails Quick Tips
In Ruby on Rails, sending emails is a common task for applications. However, during development, it's essential to avoid accidentally sending real emails to users. This is where the letter_opener gem comes in handy. This tutorial will guide you through setting up and using the letter_opener gem to preview emails in your Rails application.
Step 1: Installation
To begin, add the letter_opener
gem to your Rails application's Gemfile by including the following line:
gem 'letter_opener'
Save the file and run bundle install
to install the gem.
Step 2: Configuration
Next, configure your development environment to use letter_opener for email previews. Open the config/environments/development.rb
file and add the following code:
config.action_mailer.delivery_method = :letter_opener
config.action_mailer.perform_deliveries = true
# optional
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
This configuration sets the delivery method to letter_opener and enables email deliveries. Replace the host
and port
values with your application's corresponding details.
Step 3: Usage
With the gem installed and configured, you can preview your emails in the browser. When your application sends an email in the development environment, letter_opener will intercept it and open it in a new tab.
You need to send an email from your application to trigger the email preview. This can be done by calling the mailer method that generates the email. For example:
class PostMailer < ApplicationMailer
def send_issue
@post = params[:post]
mail(to: "[email protected]", subject: @post.title)
end
end
In your controller or wherever you want to send the email, call the mailer method:
PostMailer.with(post: @post).send_issue.deliver_now
Once the email is triggered, a new browser tab will automatically open, displaying the preview of the email generated by letter_opener.
Step 4: Customization
The letter_opener gem allows you to customize the email preview by providing additional options. For example, you can specify the location where the previews are saved or customize the URL path. Refer to the letter_opener GitHub repository for detailed customization options.
This tutorial explored how to use the letter_opener gem with Ruby on Rails to preview emails during development. Following the installation, configuration, and usage steps outlined here, you can easily ensure that your application does not accidentally send real emails while testing and developing. Enjoy hassle-free email testing with letter_opener!
For more advanced usage and customization options, remember to consult the official letter_opener documentation.
Categories
Collection
Part of the Rails Quick Tips collection
Products and courses
-
Hello Hotwire
A course on Hotwire + Ruby on Rails.
-
Hello Rails
A course for newcomers to Ruby on Rails.
-
Rails UI
UI templates and components for Rails.