Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I capture the output of an email in Rails and put it in a variable

The output from an email sent from ActionMailer output to the log, I wanted to know if I could get that output into a variable so I can store it in a file.

Ps. I forgot to mention that this is on Rails 2

like image 695
concept47 Avatar asked Apr 28 '11 17:04

concept47


2 Answers

As McStretch has pointed out, observer is the best way to handle every message that is delivered by a mailer. However, if you'd like to just capture 1 or 2 special cases, you can do the following:

Assuming you have an ActionMailer subclass called MyMailer, and an email called foobar,

# Rails 2.x
mail = MyMailer.create_foobar(...) # instead of MyMailer.deliver_foobar(...)
File.open('filename.txt', 'wb') {|f| f.write(mail.body) }
MyMailer.deliver(mail)

# Rails 3.x
mail = MyMailer.foobar(...) # instead of MyMailer.foobar(...).deliver
File.open('filename.txt', 'wb') {|f| f.write(mail.body) }
mail.deliver
like image 95
John Douthat Avatar answered Oct 29 '22 22:10

John Douthat


You can use the register_interceptor or register_observer methods on ActionMailer to do something before or after sending the mail, respectively. The ActionMailer docs state:

Action Mailer provides hooks into the Mail observer and interceptor methods. These allow you to register objects that are called during the mail delivery life cycle.

An observer object must implement the :delivered_email(message) method which will be called once for every email sent after the email has been sent.

An interceptor object must implement the :delivering_email(message) method which will be called before the email is sent, allowing you to make modifications to the email before it hits the delivery agents. Your object should make and needed modifications directly to the passed in Mail::Message instance.

Each of these methods provide a Mail::Message as an argument, so you should be able to get the desired data from that object and save it somewhere:

class  MyInterceptor
  def self.delivering_email(mail)
    # do something before sending the email
  end
end

class MyObserver
  def self.delivered_email(mail)
     # do something after sending the email
  end
end
  • Example above from http://blog.envylabs.com/2010/04/new-in-rails3-beta2/
like image 33
McStretch Avatar answered Oct 29 '22 22:10

McStretch