RubyOnbRails - 将邮件渲染为字符串

时间:2013-09-04 13:25:24

标签: ruby-on-rails

我有一个RubyOnRails 3.2.x应用程序,它使用Actionmailer发送邮件。

代码如下:

class Mymailer < ActionMailer::Base

    def sendout
        mail(:to->"someone@somewhere.com", :from ...........
    end

end

我希望将其呈现为字符串,然后我计划以不同方式处理

,而不是发送该电子邮件。

PS:在我的具体情况下,我想将该字符串传递给将实际发送邮件的Node.JS服务器,我使用RubyOnRails来处理多语言支持和数字格式化(是的,我有多个模板对于我支持的不同语言。)

2 个答案:

答案 0 :(得分:4)

由于Ruby不会发送电子邮件,因此无需使用Mailer

理想情况下,您可以生成电子邮件的JSON字符串表示形式,如:

# at the top of the file
require 'json'

# then in your method
json_string = { 
  :to => "email@example.com",
  :from =>"sender@example.com",
  :body => "this is the body"
}.to_json

然后将此字符串发送到您的node.js服务器(例如)您的控制器或当前正在调用您邮件的任何内容。

但是,由于您希望使用模板来渲染电子邮件,这些模板会引入数据库字段并使用Rails的i18n功能,您可以使用Mailer但将结果呈现为如下字符串:

mail(to: "mail@example.com") do |format|
  format.html do
    string = render_to_string("your_template")

    call_node_js(string)
  end
end

答案 1 :(得分:0)

如果你想要的是获得整个邮件表示,包括标题,那么你可能想要浏览源代码以查看幕后发生的事情。

一个很好的起点是ActionMailer::Base方法#mail(Rails 4):
http://api.rubyonrails.org/classes/ActionMailer/Base.html#method-i-mail

无论如何,如果发送是由Node.js处理的,则不需要这样做。只需构建一个像Olly建议的JSON对象并传递它。