Search code examples
ruby-on-railsactionmailerobserver-pattern

ActionMailer Observer not working


I defined an ActionMailer Observer and it's not being called. How can I go about troubleshooting this? Rails 3.1.3, Ruby 1.9.2. Alternatively, I want a method called whenever an email is sent form a certain ActionMailer subclass. This is the only clean way I could find to implement this (I could call a method from each mailing method in the ActionMailer subclass, but that's not very DRY). Any other suggestions as to how to accomplish this would be welcome.

config/initializers/mail_observer.rb:
  class MailObserver
    def self.delivered_email(message)
      require 'ruby-debug' ; debugger
      user = User.find_by_email(message.to[0])
      if user
        email_type = caller[1]
        UserMailerLogging.create!(user_id: @user.id, email_type: email_type, contents: self.body)
      end
    end
  end

  ActionMailer::Base.register_observer(MailObserver)

app/mailers/user_mailer:
  class UserMailer < ActionMailer::Base
    default from: "[email protected]"
    ...
    def unfinished_setup(user)
      @user = user
      mail to: user_email(user), subject: "Testing..."
    end
    ...
  end

And, in the Rails Console:

irb(main):001:0> UserMailer.unfinished_setup(User.find(1))    
=> #<Mail::Message:70192154395900, Multipart: false, Headers: <From: [email protected]>, <To: Test User<[email protected]>>, <Subject: Testing...>, <Mime-Version: 1.0>, <Content-Type: text/plain>>

Solution

  • I believe the observer won't fire until you actually deliver the message. Your code in the rails console is only creating the email, not sending it. Adding .deliver to the end should deliver the message and execute the observer code.