2011-11-01 72 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