简体   繁体   English

如何在Rails 3中强制HTML电子邮件的字符编码?

[英]How to force the character encoding of HTML e-mails in Rails 3?

I'm using Rails 3.1 (3.1.1 RC1) and I have configured ActionMailer to use windows-1252 as default encoding. 我正在使用Rails 3.1(3.1.1 RC1)并且我已将ActionMailer配置为使用windows-1252作为默认编码。 (External requirement) (外部要求)

This works perfectly with plain text mails, but as soon as I send HTML mails the text is converted to UTF-8 again resulting in garbled text. 这与纯文本邮件完美配合,但只要我发送HTML邮件,文本就会再次转换为UTF-8 ,从而导致文本乱码。

Here's what I've done/found out. 这是我做过/发现的事情。

  • I configured the default encoding: ActionMailer::Base.default :charset => 'windows-1252' 我配置了默认编码: ActionMailer::Base.default :charset => 'windows-1252'
  • My .erb template is actually windows-1252 encoded. 我的.erb模板实际上是windows-1252编码的。
  • I added the required marker <%# encoding: windows-1252 -%> as the first line of the template. 我添加了所需的标记<%# encoding: windows-1252 -%>作为模板的第一行。
  • The mail has a correct content type header: Content-Type: text/html; charset="windows-1252" 邮件具有正确的内容类型标题: Content-Type: text/html; charset="windows-1252" Content-Type: text/html; charset="windows-1252"

Here's the code snippet I'm using to send the mail: 这是我用来发送邮件的代码片段:

mail(:to => ..., :subject => "...") do |format|
  format.html
end    

I suspect that somehow during mail processing Rails/ActionMailer decides to convert the characters to UTF-8. 我怀疑在邮件处理过程中,Rails / ActionMailer决定将字符转换为UTF-8。 How can I change that? 我怎么能改变呢?

You don't mention what version of Ruby you are using (1.9.x do things differently then 1.8.x,) but assuming you are using a 1.9 version, you can set the following in your application.rb: 您没有提到您正在使用的Ruby版本(1.9.x以与1.8.x不同的方式执行操作),但假设您使用的是1.9版本,则可以在application.rb中设置以下内容:

config.encoding = "windows-1252"

Which will set an application wide encoding. 这将设置应用程序范围的编码。 (which is utf-8 by default) (默认为utf-8)

You should try to use the charset option within the mailer. 您应该尝试使用邮件程序中的charset选项。

See here: http://railsdispatch.com/posts/actionmailer 请参见此处: http//railsdispatch.com/posts/actionmailer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM