(这是一个老问题,但 Rails 已经发展,所以我分享在 Rails 5.2 中对我有用的东西。)
通常,您可能希望使用自定义视图助手来呈现电子邮件的主题行以及 HTML。如果视图助手位于 app/helpers/application_helper.rb 中,如下所示:
module ApplicationHelper
def mydate(time, timezone)
time.in_time_zone(timezone).strftime("%A %-d %B %Y")
end
end
我可以创建一个动态电子邮件主题行和模板,它们都使用帮助程序,但我需要告诉 Rails 在 apps/mailer/user_mailer.rb 中以两种不同的方式显式使用 ApplicationHelper,如您可以在此处的第二行和第三行中看到:
class UserMailer < ApplicationMailer
include ApplicationHelper # This enables me to use mydate in the subject line
helper :application # This enables me to use mydate in the email template (party_thanks.html.erb)
def party_thanks
@party = params[:party]
mail(to: 'user@domain.com',
subject: "Thanks for coming on #{mydate(@party.created_at, @party.timezone)}")
end
end
我应该提到这两行同样有效,因此请选择其中之一:
helper :application
add_template_helper(ApplicationHelper)
FWIW,app/views/user_mailer/party_thanks.html.erb 中的电子邮件模板如下所示:
<p>
Thanks for coming on <%= mydate(@party.created_at, @party.timezone) %>
</p>
app/controller/party_controller.rb 控制器看起来像这样
class PartyController < ApplicationController
...
def create
...
UserMailer.with(party: @party).party_thanks.deliver_later
...
end
end
我必须同意 OP (@Tom Lehman) 和 @gabeodess 的观点,考虑到https://guides.rubyonrails.org/action_mailer_basics.html#using-action-mailer-helpers,这一切都让人感到非常复杂,所以也许我遗漏了什么......