Mailers

Learn to use mailcatcher to configure email sending in Ruby on Rails.

Overview

We want to touch briefly on some other parts of Rails that we had termed boundary classes back in the Rails Application Architecture lesson. Like controllers and jobs, rake tasks are a mechanism for triggering business logic. Mailers, like views, render output for a user. Both rake tasks and Mailers exist at the outside of the app, interacting with the outside world, just as a controller does.

This section of the course will focus on mailers and rake tasks. We’ll mention Mailboxes, Action Cable, and Active Storage only briefly because we have not used these parts of Rails in production. We don’t want to give advice on something we haven’t actually used. Let’s start with mailers.

Mailers are a bit of an unsung hero in Rails apps. Styling and sending email is not an easy thing to do and yet Rails has a good system for handling it. It has an API almost identical to rendering web views, it can handle text and HTML emails, and connecting to any reasonable email provider is possible with a few lines of configuration. And it can all be tested.

There are three things to consider when writing mailers. The first is to understand the purpose of a mailer and thus not put business logic in it. Second, understand that mailers are really jobs, so the arguments they receive must be considered carefully. Last, we need a way to actually look at our emails while styling them, as well as while using the app in development mode.

Let’s start with the purpose of mailers.

Mailers should just format emails

Like controllers, we want our mailers to avoid having any business logic in them. The purpose of a mailer is to render an email based on data passed into it. That’s it. For example, our widget creation code has logic that sends the finance team an email if the widget’s price is above $7,500. We might think it’s a good idea to encapsulate the check on the widget’s price in the mailer itself. There is no real advantage to doing this, and it will only create sustainability problems later.

First, it requires executing the mailer to test ...