2011-11-01 74 views
3

因此,Rails具有发送明文电子邮件和HTML电子邮件的奇妙功能。Rails HTML转义明文电子邮件

您只需将.text.erb放在您的.html.erb旁边。我在这里为此提出了一个应用程序:https://github.com/cairo140/rails-email-test。只需下载并运行。访问主页并检查日志。

下面是输出:

Sent mail to [email protected] (19ms) 
Date: Tue, 01 Nov 2011 14:48:59 -0400 
From: [email protected] 
To: [email protected] 
Message-ID: <[email protected]l> 
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: <[email protected]l> 

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: <[email protected]l> 

<!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-- 

现在,这是文本视图(app/views/application_mailer/index.text.erb):

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

Escaped: &amp; 

ERB: <%= "&" %> 

正如你所看到的,所产生的文本电子邮件overescaped。

有什么办法可以防止这种情况发生?


进一步澄清:

如果surpress的HTML电子邮件,只发送文本,您在电子邮件客户端(我使用Gmail)得到这样的:

email body

正如你所看到的,第三行是过度使用的。

很明显,你可以在每ERB标签调用html_safe每串,或raw,但肯定的是,必须有一种方式来获得的Rails/Erubis认识到一个事实,即它是在一个文本的电子邮件,并相应地逃脱。

+0

避免太多'raw'我会创建一些帮助方法预处理整个电子邮件。事实上,知道Rails是否处理不同的文本电子邮件会很有趣 – apneadiving

回答

5

有一个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