如何通过deliver_now以HTML格式发送电子邮件,而不是单独的类

时间:2016-06-01 01:51:52

标签: ruby-on-rails

我很好奇我是否可以将以下内容作为HTML电子邮件发送而无需将其设为自己的类:

  def self.hourly
    puts "here is hourly"
    page_views=PageView.where('created_at > ?',Time.now-1.hour)
    str=ActionView::Base.new(
        Rails.configuration.paths["app/views"]).render(
        :partial => 'stats/page_views',
        :locals => { page_views: page_views })
    ActionMailer::Base.mail(from: 'from@domain.com', to: 'jon@domain.com', subject: "Welcome to My Awesome Site", body: str).deliver_now

  end

目前以文字形式发送。

修改

我对此进行了调整,但我得到了以下模板错误:

ActionMailer::Base.mail(from: 'from@domain.io', to: 'jon@jon.com', subject: "Welcome to My Awesome Site") do |format|
   format.html { render html: "<h1>Hey there</h1>".html_safe }
 end.deliver_now

我明白了:

[1] pry(main)> MyStats.hourly
here is hourly

ActionMailer::Base#mail: processed outbound mail in 15.1ms
ActionView::MissingTemplate: Missing template action_mailer/base/mail with "mailer". Searched in:
  * "action_mailer/base"
from /Users/jt/.rvm/gems/ruby-2.3.0/gems/actionmailer-4.2.6/lib/action_mailer/base.rb:916:in `each_template'

1 个答案:

答案 0 :(得分:2)

来自ActionMailer::Base.mail的文档:

  

您甚至可以直接渲染纯文本而无需使用模板:

mail(to: 'mikel@test.lindsaar.net') do |format|
  format.text { render plain: "Hello Mikel!" }
  format.html { render html: "<h1>Hello Mikel!</h1>".html_safe }
end

所以我相信你可以在你的例子中做到这样的事情:

ActionMailer::Base.mail(from: 'from@domain.com', to: 'jon@domain.com', subject: "Welcome to My Awesome Site") do |format|
  format.html { render html: str.html_safe }
end.deliver_now