I'd like to run some code whenever an email is sent on my app.

As ActionMailer doesn't support after_filter, I would like to use an observer.

The Rails docs mention this in passing, however does not elaborate.



I'm surprised how little there is in Rails' documentation about this.

Basically, ActionMailer in Rails 3 introduces the use of Interceptors (called before the message is sent) and Observers (after the message is sent).

To set up an Observer, add the following to an initializer:

class MailObserver
  def self.delivered_email(message)
    # Do whatever you want with the message in here


Now, the delivered_email method will run every time your app sends an e-mail. However, you will only have access to the actual Mail message.

To register an Interceptor instead, do the same as above, replacing register_observer with register_interceptor, and renaming the method from self.delivered_email to self.delivering_email.

This Railscast was the best source I could find for info on this (they only talk about interceptors, but the concept is the same for observers).

  • 1
    Thanks dmarkow, this is exactly what I was looking for, and as you said, information is scarce, especialy when you don't know the term "Interceptors" is one to look for. – thomasfedb Feb 28 '11 at 9:41
  • 15
    This raises some more questions - (1) How would you tell which mailer and which method was used, (2) How would you observe failure and (3) How would you test this, including the failure case? – user1158559 Dec 16 '12 at 10:06
  • 1
    I can confirm this also works in Rails 4 – Asfand Qazi Apr 8 '14 at 15:01

Your Answer

