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

ibl*_*lue 6 ruby ruby-on-rails erb actionmailer ruby-on-rails-3

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

message_from_user.text.erb:

Hi <%= @recipient.name %>,

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

<%= @message %>
Run Code Online (Sandbox Code Playgroud)

如果@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 .

任何帮助是极大的赞赏!

ibl*_*lue 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
Run Code Online (Sandbox Code Playgroud)

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


Han*_*eld 6

尝试

<%= @message.html_safe %>
Run Code Online (Sandbox Code Playgroud)

如果您使用过搜索功能,就会找到这个答案.如果这不符合您的需求,也许检查

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

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