How to intercept ActionMailer's messages on rails 3?

筅森魡賤 提交于 2019-12-06 09:01:17

问题


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?


回答1:


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.




回答2:


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?


来源:https://stackoverflow.com/questions/7272960/how-to-intercept-actionmailers-messages-on-rails-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!