Maher4Ever
Maher4Ever

Reputation: 1280

How to intercept ActionMailer's messages on rails 3?

I'm trying to intercept messages in my rails (3.0.10) app to modify the body. While I was able to find some info about how to do that, it seems something has changed and now using the old methods no longer work.

I use a code that looks like this:

class Hook
  def self.delivering_email(message)
    message.subject = 'Hook changed the subject'
  end
end

ActionMailer::Base.register_interceptor(Hook)

After sending an email, the subject doesn't get changed!

I also found a tweet that indicates that interceptors are not called when using the deliver method on messages, but the premailer-rails3 gem uses the same approach I used and it works there (The plugin specifically mentions it works with the deliver method)!

I'm out of ideas here, so what is causing my problem?

Upvotes: 3

Views: 2560

Answers (2)

user783774
user783774

Reputation:

see RailsCast or AsciiCast Episode #206

http://railscasts.com/episodes/206-action-mailer-in-rails-3

http://asciicasts.com/episodes/206-action-mailer-in-rails-3

Relevant part from the first episode,

/lib/development_mail_interceptor.rb

class DevelopmentMailInterceptor
  def self.delivering_email(message)
    message.subject = "[#{message.to}] #{message.subject}"
    message.to = "[email protected]"
  end
end

/config/initializers/setup_mail.rb

Mail.register_interceptor(DevelopmentMailInterceptor) if Rails.env.development?

Upvotes: 5

Winfield
Winfield

Reputation: 19145

It sounds like it might be an order of operations problem.

Have you considered putting the entire code block you referenced in an initializer like config/initializers/mail_hook.rb?

If that premailer plugin works, the only difference I can think of is when the interception hook is registered in the app initialization process.

Upvotes: 5

Related Questions