【问题标题】:Rails escapes HTML in my plain text mailsRails 在我的纯文本邮件中转义 HTML
【发布时间】:2012-08-10 05:58:20
【问题描述】:

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

message_from_user.text.erb:

Hi <%= @recipient.name %>,

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

<%= @message %>

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

我的应用程序中有很多邮件模板,它们都是纯文本。我会考虑修补所有这些以包含 &lt;%=raw @message%&gt;&lt;%= @message.html_safe %&gt; 糟糕的风格 - 不是很干燥

我尝试了各种变通方法,包括修补 Erubis 的钱。它们似乎都不起作用。我正在寻找一些补丁或配置选项或任何东西来禁用所有.text.erb 文件的转义html。

非常感谢任何帮助!

【问题讨论】:

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


    【解决方案1】:

    在通过 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 实体。

    【讨论】:

      【解决方案2】:

      试试

      <%= @message.html_safe %>
      

      如果您使用了搜索功能,您就会找到这个答案。如果这不适合您的需求,请检查

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

      如果您还没有看到,这里讨论了一些选项

      【讨论】:

      • 感谢您的回答,但正如问题中所述,这不是我的选择。 “[...] 我会考虑修补所有内容以包含 糟糕的风格 - 不是很干燥。”
      • 抱歉,边吃边看的效果似乎没有我想象的那么好;)我添加了一个额外的链接,这里对这个问题进行了更深入的讨论。如果您还没有阅读,也许它会有所帮助
      猜你喜欢
      • 1970-01-01
      • 2011-09-28
      • 2014-04-21
      • 1970-01-01
      • 2015-06-15
      • 2020-12-01
      • 2011-09-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多