7

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

我正在使用 Rails 2.3.8。

我在这里读到了这个猴子补丁......但这似乎表明新版本的rails已经结束了?如果我能避免的话,我真的不想要猴子补丁。

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

我也有2个文件。

email.text.html.erb
email.text.plain.erb

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

4

3 回答 3

9

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

layout.text.html.erb    => layout.html.erb
layout.text.plain.erb   => layout.text.erb

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

part :content_type => 'text/plain',
     :body => render_message('my_template')

然后 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

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

我知道,离实际解决方案不远了。ActionMailer 内部对我来说太不透明了。

于 2010-09-14T14:10:16.313 回答
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

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

layout "email", :except => [:send_inquiry]

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

于 2010-09-10T16:08:35.570 回答
0

我发现这个我认为可能有用。

http://blog.blazingcloud.net/2009/11/17/simple-email-form-with-actionmailer/

他利用重命名不同内容类型的视图模板。

于 2012-05-24T11:13:45.797 回答