8

I want to keep track of all triggered emails by the application into a db table, so that i can have a log which emails are sent and to whom.

Kindly suggest me the best possible solution.

Baran
  • 1,114
  • 1
  • 10
  • 25
  • 1
    Have a look at this answer: http://stackoverflow.com/questions/4850484/how-do-i-create-a-mailer-observer/5131614#5131614 – eugen Nov 05 '13 at 10:00

2 Answers2

7

I have solved this using the following way:

created a class in lib directory

class MyProjectMailLogger

  def self.delivering_email(message)
   @to = message.to.to_s
   @subject = message.subject.to_s
   @message = message.body.to_s
   EmailQueue.create!(:receipient_email => @to, :subject => @subject, :message => @message, :email_status_id => 3)
 end

end

In config/initalizers/setup_mail.rb

ActionMailer::Base.register_interceptor(MyProjectMailLogger)

You might need to add the following line in the application.rb file as its not include files from lib directory:

config.autoload_paths += %W(#{config.root}/lib)

Yay!! and i logged my emails.

Baran
  • 1,114
  • 1
  • 10
  • 25
  • 1
    I had to implement something very similar to your solution, except I used ActionMailer::Base.register_observer(..) for that. This worked well, but now I have to implement a way to re-send any of the emails from the "email log", with all attachments. Now wondering how do I do that... – Alex Kovshovik Feb 08 '15 at 22:18
0

I am doing some research on this and it seems like https://github.com/ankane/ahoy_email is a nice gem to accomplish this. It uses an interceptor internally like the accepted answer. It also integrates with a free event tracking library that has a number of different backends. Might be something to consider if you're starting something like this today.

Anthony Panozzo
  • 3,274
  • 1
  • 24
  • 22