Augustin Riedinger
Augustin Riedinger

Reputation: 22170

Duplicate mail with mail_interceptor in Rails

I have set up a mail interceptor, but I can't make it duplicate the email as I'd like.

class MailDuplicator
  def self.delivering_email(message)

    copy = message
    copy.subject = "[Duplicata] To: #{message.to} - #{message.subject}"
    copy.to = "Logger <[email protected]>"
    copy.deliver

    return message
  end
end

Am I doing something wrong?

Upvotes: 0

Views: 132

Answers (1)

Augustin Riedinger
Augustin Riedinger

Reputation: 22170

Found the solution: don't use mail_interceptor, but mail_observer, which is called after the mail is sent.

# LIB (/lib/mail_duplicator.rb)
class MailDuplicator
  def self.delivered_email(message)
    duplicate_email = '[email protected]'

    if !message.to.include?(duplicate_email) # Avoid stack level too deep error
      message.subject = "[Duplicata] To: #{message.to} - #{message.subject}"
      message.to = duplicate_email

      message.deliver
    end

    return message
  end
end


# INITALIZER (/config/initializers/setup_mail.rb)
require 'mail_duplicator'
ActionMailer::Base.register_observer(MailDuplicator)

Though I still haven't managed to duplicate the Mail::Message object as I wanted to do at first ...

Upvotes: 1

Related Questions