0
0
Ruby on Railsframework~5 mins

Email previews in Ruby on Rails

Choose your learning style9 modes available
Introduction

Email previews let you see how your emails will look before sending them. This helps catch mistakes and improve design.

You want to check the layout and content of a welcome email before sending it to users.
You need to verify that dynamic data like user names appear correctly in emails.
You want to test different email templates without sending real emails.
You want to quickly review changes after updating email styles or text.
You want to share a draft of an email with your team for feedback.
Syntax
Ruby on Rails
class UserMailerPreview < ActionMailer::Preview
  def welcome_email
    user = User.first
    UserMailer.with(user: user).welcome_email
  end
end
Email preview classes go in the test/mailers/previews folder by default.
Each method in the preview class returns a mail object to display in the browser.
Examples
This preview shows the alert email for the last user in the database.
Ruby on Rails
class NotificationMailerPreview < ActionMailer::Preview
  def alert_email
    user = User.last
    NotificationMailer.with(user: user).alert_email
  end
end
This preview displays the receipt email for the first order.
Ruby on Rails
class OrderMailerPreview < ActionMailer::Preview
  def receipt_email
    order = Order.first
    OrderMailer.with(order: order).receipt_email
  end
end
Sample Program

This example defines a simple welcome email and a preview that shows it for a sample user named Alice.

Ruby on Rails
class UserMailer < ApplicationMailer
  def welcome_email
    @user = params[:user]
    mail(to: @user.email, subject: "Welcome to Our Site")
  end
end

class UserMailerPreview < ActionMailer::Preview
  def welcome_email
    user = User.new(name: "Alice", email: "alice@example.com")
    UserMailer.with(user: user).welcome_email
  end
end
OutputSuccess
Important Notes

You can access previews in your browser at http://localhost:3000/rails/mailers when running Rails locally.

Previews do not send real emails; they only render the email content for review.

Use sample or dummy data in previews to avoid exposing real user information.

Summary

Email previews help you see emails before sending.

Create preview classes with methods that return mail objects.

View previews in the browser to check email content and design.