html - Rails HTML 转义纯文本电子邮件

标签 html ruby-on-rails erubis

因此,Rails 具有发送纯文本电子邮件和 HTML 电子邮件的绝妙功能。

您只需在 .html.erb 旁边放置一个 .text.erb。我在这里提出了一个申请:https://github.com/cairo140/rails-email-test .只需下载并运行。访问主页并查看日志。

这是输出:

Sent mail to test@test.com (19ms)
Date: Tue, 01 Nov 2011 14:48:59 -0400
From: test@test.com
To: test@test.com
Message-ID: <4eb03f1b7403b_178858111fcc060bd@Steven-Xus-Macbook-Pro.local.mail>
Subject: test
Mime-Version: 1.0
Content-Type: multipart/alternative;
 boundary="--==_mimepart_4eb03f1b708ce_178858111fcc057a4";
 charset=UTF-8
Content-Transfer-Encoding: 7bit



----==_mimepart_4eb03f1b708ce_178858111fcc057a4
Date: Tue, 01 Nov 2011 14:48:59 -0400
Mime-Version: 1.0
Content-Type: text/plain;
 charset=UTF-8
Content-Transfer-Encoding: 7bit
Content-ID: <4eb03f1b72b72_178858111fcc058ce@Steven-Xus-Macbook-Pro.local.mail>

Unescaped: &

Escaped: &amp;

ERB: &amp;


----==_mimepart_4eb03f1b708ce_178858111fcc057a4
Date: Tue, 01 Nov 2011 14:48:59 -0400
Mime-Version: 1.0
Content-Type: text/html;
 charset=UTF-8
Content-Transfer-Encoding: 7bit
Content-ID: <4eb03f1b73784_178858111fcc05933@Steven-Xus-Macbook-Pro.local.mail>

<!doctype html>
<html>
  <head>
    <title>test</title>
  </head>
  <body>
    <ul>
      <li>Unescaped: &</li>
      <li>Escaped: &amp;</li>
      <li>ERB: &amp;</li>
    </ul>
  </body>
</html>


----==_mimepart_4eb03f1b708ce_178858111fcc057a4--

现在,这是 TextView (app/views/application_mailer/index.text.erb):

$ cat app/views/application_mailer/index.text.erb 
Unescaped: &

Escaped: &amp;

ERB: <%= "&" %>

如您所见,生成的文本电子邮件被过度转义。

有什么办法可以避免这种情况吗?


进一步说明:

如果您隐藏 HTML 电子邮件并只发送文本,您会在电子邮件客户端中收到此信息(我使用的是 Gmail):

email body

如你所见,第三行被过度转义了。

显然,您可以在每个字符串上调用 html_safe,或者在每个 ERB 标记上调用 raw,但是肯定有办法让 Rails/Erubis 识别事实上它在文本电子邮件中并相应地转义。

最佳答案

有一个 thread在 Rails 的灯塔中讨论这个问题和 monkey patch也试图修复它。尝试将其放入初始化器中并试一试。

# fix_erubis_non_escape_sequence.rb
module ActiveSupport
  class SafeBuffer < String
    alias safe_append= safe_concat
  end
end

module ActionView
  class Template
    module Handlers
      class Erubis < ::Erubis::Eruby
        def add_expr_escaped(src, code)
          if code =~ BLOCK_EXPR
            src << "@output_buffer.safe_append= " << code
          else
            src << "@output_buffer.safe_concat((" << code << ").to_s);"
          end
        end
      end
    end
  end
end

关于html - Rails HTML 转义纯文本电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7971461/

相关文章:

ruby-on-rails - 奇怪的 && 运算符行为?

ruby-on-rails - 在 rails 中间件中访问路由

html - 使用 Nodemailer 将表单输入中的数据发送到电子邮件

PHP导航菜单

ruby-on-rails - 修改时 Rails 控制台输出中断

javascript - 在 javascript Assets 中使用 Rails 辅助方法

ruby - 在使用 erubis 的 sinatra 中,默认设置 escape_html 为真。有时不得不逃避

html制作一个带有垂直列的表格

javascript - 我可以在选择元素的选项中使用 HTML 标签吗?