Here is what I ended up with ... I would like to receive feedback on the pros and cons of this. It feels ugly for me, but it was easy. Basically, I turned on the ability to use callbacks in my mail program by attaching the class and method name metadata to the Mail::Message object so that it is available in my observer. I bound it by setting the instance variables in the Mail::Message object, and then sending attr_reader to the Mail::Message class, calling me to call mail.mailer_klass and mail.mailer_action .
I did it this way because I wanted to record the Mail::Message object after it was delivered, so that I could get the exact date it was sent, and I know that the registered email must be sent successfully.
Sender:
class MyMailer < ActionMailer::Base default from: " noreply@theapp.com " include AbstractController::Callbacks
Observer:
class MailAuditor def self.delivered_email(mail) if mail.multipart? body = mail.html_part.decoded else body = mail.body.raw_source end Email.create!( sender: mail.from, recipient: mail.to, bcc: mail.bcc, cc: mail.cc, subject: mail.subject, body: body, mailer_klass: mail.mailer_klass, mailer_action: mail.mailer_action, sent_at: mail.date ) end end
configurations / Initializers / mail.rb
ActionMailer::Base.register_observer(MailAuditor)
Thoughts?
source share