Ste*_*ven 3 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: &
ERB: &
----==_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: &</li>
<li>ERB: &</li>
</ul>
</body>
</html>
----==_mimepart_4eb03f1b708ce_178858111fcc057a4--
Run Code Online (Sandbox Code Playgroud)
现在,这是文本视图(app/views/application_mailer/index.text.erb):
$ cat app/views/application_mailer/index.text.erb
Unescaped: &
Escaped: &
ERB: <%= "&" %>
Run Code Online (Sandbox Code Playgroud)
如您所见,生成的文本电子邮件已经过时.
有什么方法可以防止这种情况吗?
进一步澄清:
如果您压缩HTML电子邮件并只发送文本,则可以在电子邮件客户端中获取此信息(我正在使用Gmail):

如你所见,第三行是过度的.
显然,你可以调用html_safe每个字符串,或者raw每个ERB标签,但肯定的是,必须有一种方法可以让Rails/Erubis识别它在文本电子邮件中的事实并相应地转义.
在rails'灯塔里有一个讨论问题的线程,还有一个试图修复它的猴子补丁.尝试将其放入初始化程序并尝试一下.
# 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
Run Code Online (Sandbox Code Playgroud)