KKK
KKK

Reputation: 1085

RubyOnbRails - Render mail to string

I have a RubyOnRails 3.2.x application that sends out mails using Actionmailer.

The code goes something like this:

class Mymailer < ActionMailer::Base

    def sendout
        mail(:to->"[email protected]", :from ...........
    end

end

Instead of sending out that email, I want it to be rendered to a string which I then plan to process differently

PS: In my specific case I want to pass that string to a Node.JS server who will do the actual sending of the mail, I am using RubyOnRails to handle the multi language support and number formatting (yes I have multiple templates for the different languages that I support).

Upvotes: 2

Views: 1378

Answers (2)

Olly
Olly

Reputation: 7758

Since Ruby won't be doing the email sending, there's no need to use the Mailer.

Ideally you could generate a JSON string representation of the email like:

# at the top of the file
require 'json'

# then in your method
json_string = { 
  :to => "[email protected]",
  :from =>"[email protected]",
  :body => "this is the body"
}.to_json

Then post this string to your node.js server from (for example) your controller or whatever is currently calling your mailer.

However, since you want to render the email using templates which pull in DB fields and use the i18n functionality of Rails, you could use the Mailer but render the result to a string like follows:

mail(to: "[email protected]") do |format|
  format.html do
    string = render_to_string("your_template")

    call_node_js(string)
  end
end

Upvotes: 4

tompave
tompave

Reputation: 12402

If what you want is getting the whole mail representation, including headers, then you might want to browse the source code to see what happens behind the curtain.

A good starting point is the ActionMailer::Base method #mail (Rails 4):
http://api.rubyonrails.org/classes/ActionMailer/Base.html#method-i-mail

Anyway, if the sending is handled by Node.js, you don't need to do it. Just build a JSON object like Olly suggested and pass it through.

Upvotes: 0

Related Questions