Rails在我的纯文本邮件中转义HTML

时间:2012-08-01 09:23:40

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

我使用rails 3.2.5 ActionMailer发送纯文本邮件。鉴于我有这样的邮件视图:

message_from_user.text.erb

Hi <%= @recipient.name %>,

You got the following message from <%= @sender.name %>:

<%= @message %>

@message"quotes & ampersands"时,纯文本邮件包含&quot;quotes &amp; ampersands&quot;。因此看起来rails只是将其视为HTML视图并转义任何html以防止跨站点脚本。但这是一封纯文本邮件。扩展名为.text.erbActionMailer检测此扩展名并将MIME设置为text/plain。所以我永远不想逃避它中的任何HTML。

我的应用程序中有很多邮件模板,它们都是纯文本。我会考虑修补所有内容以包含<%=raw @message%><%= @message.html_safe %>错误的样式 - 不是非常干

我尝试过varios解决方案,其中包括修补Erubis的钱。他们似乎都没有工作。我正在寻找一些补丁或配置选项或任何东西来禁用所有.text.erb文件的转义html。

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:8)

通过Erubis代码调试几个小时后,我发现了以下修复程序。你可以把它放进config/initializers/fix_my_mails.rb。我用rails 3.2.7测试了这个。它可能适用于其他版本。

module ActionView
  class Template
    module Handlers
      class ERB
        def call(template)
          if template.source.encoding_aware?
            # First, convert to BINARY, so in case the encoding is
            # wrong, we can still find an encoding tag
            # (<%# encoding %>) inside the String using a regular
            # expression
            template_source = template.source.dup.force_encoding("BINARY")

            erb = template_source.gsub(ENCODING_TAG, '')
            encoding = $2

            erb.force_encoding valid_encoding(template.source.dup, encoding)

            # Always make sure we return a String in the default_internal
            erb.encode!
          else
            erb = template.source.dup
          end

          self.class.erb_implementation.new(
            erb,
            :trim => (self.class.erb_trim_mode == "-"),
            :escape => template.identifier =~ /\.text/ # only escape HTML templates
          ).src
        end
      end
    end
  end
end

它只是在文件名中包含.text的每个erb文件中禁用HTML实体。

答案 1 :(得分:6)

尝试

<%= @message.html_safe %>

如果您使用过搜索功能,则会找到此答案。如果这不符合您的需求,请检查

https://rails.lighthouseapp.com/projects/8994/tickets/4858-actionmailer-is-html-escaping-ampersand-in-urls-in-plain-text-messages

如果你还没有看到,那里会讨论一些选项