【问题标题】:Rails mailer and mailer views in subfolder not working子文件夹中的 Rails 邮件程序和邮件程序视图不起作用
【发布时间】:2013-12-19 01:56:46
【问题描述】:

我可以在日志中看到一个邮件程序正在发送,但邮件正文不包含邮件程序视图中的任何内容。

这是因为我将东西放在子文件夹中,并且我尝试在我的 mail 函数中使用 :template_path 但无济于事。

app/mailers/marketing/marketing_mailer.rb

class Marketing::MarketingMailer < ActionMailer::Base

    require 'mail'
    address = Mail::Address.new "test@example.com" # ex: "john@example.com"
    address.display_name = "Text" # ex: "John Doe"
    # Set the From or Reply-To header to the following:
    address.format # returns "John Doe <john@example.com>"
    default from: address

    # Sends an email when someone fills out the contact form
    def contact(name, email, message)
        @name = name
        @email = email
        @message = message
        mail(:subject => "Test", :to => 'test@example.com', :reply_to => @email) # <== I've tried using :template_path => 'marketing', 'marketing/marketing_mailer', etc, but none worked.
    end
end

/app/views/marketing/marketing_mailer/contact.html.erb

<!DOCTYPE html>
<html>
  <head>
    <meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
  </head>
  <body>
    <p>Name: <%= @name %></p>
    <p>Email: <%= @email %></p>
    <p>Message: <%= @message %></p>
  </body>
</html>

我注意到 devise 在 /views/devise/mailers/... 中有邮件视图,所以我知道这是可能的,但我不确定如何。

【问题讨论】:

  • 这取决于您使用的 Rails 版本。请提及您的 Rails 版本
  • @SatyaKalluri 我看到了那个答案并尝试了 template_path。其他一些答案似乎引发了弃用警告和其他东西。

标签: ruby-on-rails ruby-on-rails-3 actionmailer


【解决方案1】:

您是否尝试过使用 {:template_path => 'marketing/marketing_mailer, :template_name =>'contact'} 发送邮件?

模板名称可能以某种方式期望文件名中的命名空间

【讨论】:

    【解决方案2】:

    没有模板渲染是否可以工作

       class Marketing::MarketingMailer < ActionMailer::Base
       def welcome_email(user, email_body)
         mail(to: user.email,
         body: email_body,
         content_type: "text/html",
         subject: "Already rendered!")
       end
       end
    

    【讨论】:

      【解决方案3】:

      我今天回到这个项目,似乎今天找到模板没问题,无需指定模板路径。

      尽管如此可悲,显然我需要做的只是停止并重新启动我的服务器,以便接收我的邮件视图。由于其他视图在不停止和启动我的服务器的情况下被拾取,我对此感到非常惊讶。

      【讨论】:

      • 我从视图模板中了解到这种行为。查找了一个模板,但当时它还不存在。服务器没有找到它,但记得它不存在。然后在下次重新启动之前不会再次查找它,即使您添加了它。
      【解决方案4】:

      由于您的文件采用.html.erb 格式,您可能必须指定要使用此格式。像这样:

      mail(:subject => "Test", :to => 'test@example.com', :reply_to => @email) do
        format.html
      end
      

      通常,由于名称匹配,您的模板应该被自动拾取,但可能还有另一个以.text.erb 结尾的同名文件或其他妨碍模板查找的东西。

      EDIT1(胡乱猜测) 除了模板查找问题之外,我能想象的唯一其他问题来源就是您的实例变量。也许@message 应该是别的东西,而您正在干扰内部结构,因此重命名它可能会有所帮助。根据 apidock 上的代码,邮件在某些地方使用@variables。我承认,这有点牵强。

      EDIT2(此处所面临问题的解释) 实际问题背后的行为 - 直到服务器重新启动才找到新模板 - 工作方式如下:

      查找了一个模板,但当时它还不存在。服务器没有找到它,但记得它不存在。然后在下次重新启动之前不会再次查找它,即使您添加了它。

      所以,重启会解决这个问题。

      您是否尝试将其关闭再打开?

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-21
      • 1970-01-01
      • 1970-01-01
      • 2012-04-22
      • 1970-01-01
      相关资源
      最近更新 更多