我想弄清楚是否可以使用不带 Rails 的 ActionMailer 渲染一次 html.erb View ,然后仅使用 :to 中的不同电子邮件将其多次发送?
注意:我没有使用完整的 Rails 堆栈,只是使用 ActionMailer
所以在邮件类
class MyMailer < ActionMailer::Base
default :from => 'johndoe@example.com',
:subject => 'New Arrivals!'
def new_products(customer, new_products)
@new_products = new_products
mail :to => customer.email do |format|
format.html
end
end
end
然后,在客户端代码中,我们需要获取新产品和客户。
products = Product.new_since_yesterday
customers = Customer.all
customers.each do |c|
MyMailer.new_products(c, products).deliver
end
假设每天发送一次,因此我们只想获取自上次发送电子邮件以来的新产品。我们只想呈现一次,因为今天的新产品不会在电子邮件之间改变。据我所知,每次创建和发送电子邮件时都会调用渲染。
有没有办法告诉 ActionMailer 只渲染一次,然后以某种方式引用包含渲染 View 的对象。这将减少渲染完成它所需的所有时间。发送到的电子邮件地址会改变,但电子邮件的内容不会。
显然,对于大量电子邮件,您不会简单地遍历列表并创建/发送电子邮件。您可能会为此使用队列。但是,一般来说,当没有必要多次生成渲染步骤时,您将如何执行一次并将该结果用于所有电子邮件?
可能是我对 ActionMailer 的不熟悉让我失望了。
最佳答案
我还没有尝试过这个,但是对邮件程序的调用只返回一个普通的旧 Mail::Message 对象,并带有一个正文。所以你应该能够捕获 body 并重新使用它。
message = MyMailer.new_products(c, products)
message_body = message.body
customers.each do |c|
mail = Mail.new do
from 'yoursite@sample.com'
to c.email
subject 'this is an email'
body message_body
end
mail.deliver
end
您甚至可以通过复制消息来获得更高的“效率”
message = MyMailer.new_products(c, products)
customers.each do |c|
mail = message.dupe()
mail.to = c.email
mail.deliver
end
关于ruby-on-rails - ActionMailer 渲染一次,发送多次?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6473248/