elements
elements

Reputation: 1057

ActionMailer- access Mail::Message content, or manually initialize view in controller?

I've got a form where an internal user can request that informational materials be sent to a client. When the form is submitted, it sends an email to the person in charge of physically mailing the materials to the client.

Now, I want to capture the content of the email so I can add a note to the client's show page, and I'm unsure how to go about it.

One option I've looked at is to use an after_filter in the MaterialsRequestMailer, but calling message.body returns a large string with way more text than I need and I want to avoid adding a bunch of parsing logic to get the message content.

Basically, I want what is generated by the views/materials_request_mailer/send_request_notification.text.erb template. I've looked through http://www.rubydoc.info/github/mikel/mail/Mail/Message and can't find a method to return just the rendered template content. Is there a way to do that?

If not, is there a way to manually initialize a View in the controller, where I already have the instance variables I'm passing to the mailer? That doesn't seem to be an ideal solution, because I'm using DelayedJob, and the code for adding the note would be run before the email is actually sent. Also, due to DelayedJob, it appears that I can't directly access the mail object from within the controller (if I do mail = MaterialsRequestMailer.delay.send_request_notification(...) it assigns an instance of Delayed::Backend::ActiveRecord::Job to mail).

Upvotes: 1

Views: 783

Answers (1)

elements
elements

Reputation: 1057

Found a solution that works- message.text_part.body.raw_source is what I was looking for. (credit to this answer: https://stackoverflow.com/a/15257098/2599738)

class MaterialsRequestMailer < ActionMailer::Base
  include AbstractController::Callbacks

  after_filter :add_note_to_client

  def send_request_notification(client, ...)
    @client = client
    ...
  end

  def add_note_to_client
    mail_text = message.text_part.body.raw_source
    @client.add_account_note(mail_text)
  end
end

Upvotes: 1

Related Questions