开发者

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?


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.


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 = "eifion@asciicasts.com"
  end
end

/config/initializers/setup_mail.rb

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜