Skip to Content
Course content

214: Action Mailer In Depth

Click on the "Edit" button in the top corner of the screen to edit your slide content.

By now, you know that Action Mailer is essentially Action Controller for emails. You've likely sent a basic "Welcome" email, but in a real production app, mailers get complicated quickly. You have to deal with different formats, complex data associations, and the inevitable frustration of CSS in emails (which is a nightmare I won't subject you to today).

Let's build a professional Order Confirmation system for a boutique coffee shop app. We aren't just sending a string of text; we want a structured email that lists the items purchased and the total cost.

Setting up the OrderMailer

First, I'll generate the mailer. I prefer keeping my mailers lean—they should handle the delivery logic, while the views handle the presentation.

rails generate mailer OrderMailer

Now, let's define the action. I want to pass in an Order object. Because Action Mailer methods are just like controller actions, any instance variable I define here will be available in the view.

class OrderMailer < ApplicationMailer
  default from: 'notifications@beanandbrew.com'

  def confirmation(order)
    @order = order
    @user = order.user

    mail(to: @user.email, subject: "Your Bean & Brew Order ##{@order.id} is confirmed!")
  end
end

The "Wait, why is this nil?" moment

I'm going to be honest: I just wrote the view for this and hit a NoMethodError immediately. Here is what I did—I tried to access @order.items in the HTML template, but I realized I had passed order as a local variable to the method without assigning it to an instance variable first.

If your mailer method looks like this: def confirmation(order); mail(to: ...); end, your view cannot see order. It must be @order. I spent five minutes questioning my sanity before realizing I missed that single @ symbol. Don't be like me; always double-check your instance variable assignments in the mailer action.

Crafting the order template

Now we need the actual email content. I always create both an HTML version for modern clients and a plain text version for the few people (and bots) who still prefer it. The HTML version is where we can make the order list look clean.

In app/views/order_mailer/confirmation.html.erb:

<h1>Thanks for your order, <%= @user.first_name %>!</h1>
<p>We're getting your beans roasted and ready to ship.</p>

<table>
  <tr>
    <th>Item</th>
    <th>Price</th>
  </tr>
  <% @order.line_items.each do |item| %>
    <tr>
      <td><%= item.product.name %></td>
      <td><%= number_to_currency(item.price) %></td>
    </tr>
  <% end %>
</table>

<p>Total: <%= number_to_currency(@order.total_price) %></p>

Triggering the mailer from the controller

Sending the email synchronously in a controller is a rookie mistake. If your SMTP server is slow, your user's browser will just hang until the email sends. Instead, we use deliver_later, which pushes the job onto Active Job to be handled in the background.

In the OrdersController, after the order is successfully saved:

def create
  @order = Order.new(order_params)
  if @order.save
    # We pass the @order object directly to the mailer method
    OrderMailer.confirmation(@order).deliver_later
    redirect_to @order, notice: 'Order was successfully placed.'
  else
    render :new
  end
end

I use deliver_later 99% of the time. The only time I use deliver_now is during local development when I'm debugging the mailer logic and want to see the result immediately without worrying about my background worker (like Sidekiq or Solid Queue) being running.




📋 Practical Task

Build a "Low Stock" Alert Mailer

You are adding a feature to the coffee shop app to notify the warehouse manager when a product's inventory drops below a certain threshold.

Your Task:

  1. Create a new mailer called InventoryMailer.
  2. Define an action called low_stock_alert that accepts a product object.
  3. Set the from address to inventory@beanandbrew.com and the to address to manager@beanandbrew.com.
  4. Create a corresponding HTML view that displays the product name and the current quantity remaining.
  5. Write a small snippet of code (as if it were in a Product model or a Service Object) that calls this mailer using deliver_later only if the product's quantity is less than 10.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.