Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a Mailer Observer

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.

Thanks!

like image 267
thomasfedb Avatar asked Jan 31 '11 11:01

thomasfedb


People also ask

How do I Preview mailers in rails?

rails generates a mail preview if you use rails g mailer CustomMailer . You will get a file CustomMailerPreview inside spec/mailers/previews folder. Here you can write your method that will call the mailer and it'll generate a preview.

What is Default_url_options?

The default_url_options setting is useful for constructing link URLs in email templates. Usually, the :host , i.e. the fully qualified name of the web server, is needed to be set up with this config option. It has nothing to do with sending emails, it only configures displaying links in the emails.


1 Answers

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   end end  ActionMailer::Base.register_observer(MailObserver) 

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).

like image 115
Dylan Markow Avatar answered Oct 03 '22 00:10

Dylan Markow