ActionMailer allows us to send emails from our application using mailer classes and views.
Callbacks are methods that get called at specific points in the lifecycle of a mailer action. With the introduction of the *_deliver
callbacks, we can now hook into the email delivery process more effectively.
Before
If we want to hook into the lifecycle of email delivery, we have to use interceptors and observers to modify, monitor, or perform actions on emails before or after they are sent.
Interceptors are used to modify or prevent the delivery of emails before they are sent out.
Observers are used to monitor the delivery of emails and perform actions when an email is delivered. Unlike interceptors, observers do not modify the email but are notified after an email has been sent.
However, while interceptors and observers offer distinct separation of concerns, they can lead to fragmented logic, limited flexibility, and more complex testing due to the need for separate classes and registrations.
After
Rails 7.1 adds *_deliver callbacks to ActionMailer which allows us to hook into the lifecycle of email delivery.
With the introduction of before_deliver, around_deliver, and after_deliver callbacks there is no need to initialize interceptors and observers.
These *_deliver callbacks helps us to manage email lifecycle events directly within the mailer, providing a more integrated and flexible approach to modifying and tracking emails before, during, and after delivery.
This enhances code maintainability and simplifies logic compared to using separate interceptors and observers.