How to get email output in Rails and put it in a variable

Exiting an email sent from ActionMailer output to a log, I wanted to know if I could get this output in a variable to save it to a file.

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

+6
source share
2 answers

As McStretch noted, an observer is the best way to process every message that is delivered by an email program. However, if you just want to capture 1 or 2 special cases, you can do the following:

Assuming you have a subclass of ActionMailer 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 
+7
source

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

Action Mailer provides hooks to the Mail Supervisor and Interceptor Methods. They allow you to register objects that are called during the mail delivery time.

The observer object must implement: the deliver_email (message) method, which will be called once for each letter sent after sending the email message.

The interceptor object must implement the method: delivering_email (message) which will be called before the email address is sent, which allows changing the email before it gets to the delivery agents. Your object must make and make the necessary changes directly to the passed Mail :: Message.

Each of these methods provides Mail :: Message as an argument, so you should be able to get the data you need from this 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 
+2
source

Source: https://habr.com/ru/post/886907/


All Articles