导轨邮件与不同的布局

hol*_*den 7 email layout ruby-on-rails multipart actionmailer

我在Notifier模型中使用了一个布局用于我的所有电子邮件(20多封电子邮件)...但有时我只想发送一个没有布局或html的纯文本电子邮件.我似乎无法弄清楚如何?如果我尝试发送纯文本电子邮件,我仍然可以获得布局,以及电子邮件中的所有HTML.

我正在使用Rails 2.3.8.

我在这里读到了关于这个猴子补丁的内容......但它似乎表明有更新版本的导轨已经过来了吗?如果我可以避免,我真的不想修补猴子.

Rails - 使用邮件程序模板为多部分电子邮件设置多个布局

  layout "email" # use email.text.(html|plain).erb as the layout


  def welcome_email(property)
    subject    'New Signup'
    recipients property.email
    from       'welcome@test.com'
    body       :property => property
    content_type "text/html"
  end

  def send_inquiry(inquire)
    subject    "#{inquire.the_subject}"
    recipients inquire.ob.email
    from       "Test on behalf of #{inquire.name} <#{inquire.email}>"
    body       :inquire => inquire
    content_type "text/plain"

  end
Run Code Online (Sandbox Code Playgroud)

我也有2个文件.

email.text.html.erb
email.text.plain.erb
Run Code Online (Sandbox Code Playgroud)

它总是使用text.html.erb ...即使content_type是"text/plain"

Pet*_*tee 9

编辑:想出来,布局遵循不同的电子邮件模板命名方案.只需将它们重命名如下:

layout.text.html.erb    => layout.html.erb
layout.text.plain.erb   => layout.text.erb
Run Code Online (Sandbox Code Playgroud)

如果你使用这个,我也犯了手动定义零件的错误:

part :content_type => 'text/plain',
     :body => render_message('my_template')
Run Code Online (Sandbox Code Playgroud)

然后Rails无法确定您的部件的content_type,并假定它是HTML.

在我改变了这两件事后,它对我有用!

原始回复如下..


过去我曾经多次努力解决这个问题,通常最终会遇到某种非干燥的快速和肮脏的解决方案.我一直以为我是唯一一个有这个问题的人因为谷歌在这个问题上没有任何用处.

这次我决定深入研究Rails,但到目前为止还没有取得多大成功,但也许我的研究结果将帮助其他人解决这个问题.

我发现在ActionMailer :: Base中,#render_message方法的任务是确定正确的content_type,并将其分配给@current_template_content_type.#default_template_format然后返回布局的正确mime类型,或者如果未设置@current_template_content_type,它将默认为:html.

这就是ActionMailer :: Base#render_message在我的应用程序中的样子(2.3.5)

  def render_message(method_name, body)
    if method_name.respond_to?(:content_type)
      @current_template_content_type = method_name.content_type
    end
    render :file => method_name, :body => body
  ensure
    @current_template_content_type = nil
  end
Run Code Online (Sandbox Code Playgroud)

问题是method_name似乎是一个字符串(本地视图的名称,在我的情况下是"new_password.text.html"),字符串当然不响应#to_content_type,这意味着@current_template_content_type将始终保持为零,因此#default_template_format将始终默认为:html.

我知道,并没有更接近实际的解决方案.ActionMailer内部对我来说太不透明了.


Mis*_*cha 5

好的,不确定这是否有效,但似乎默认的content_type是text/plain,所以如果你想要text/plain以外的东西,你只需要设置内容类型.

试试这个:

def send_inquiry(inquire)
  subject    "#{inquire.the_subject}"
  recipients inquire.ob.email
  from       "Test on behalf of #{inquire.name} <#{inquire.email}>"
  body       :inquire => inquire
end
Run Code Online (Sandbox Code Playgroud)

我仍然认为你应该考虑这个:

layout "email", :except => [:send_inquiry]
Run Code Online (Sandbox Code Playgroud)

我会使用上面的内容,因为纯文本电子邮件似乎没有"布局",只有您要发送的实际内容.