ruby mail gem - 在交付块中设置charset

时间:2013-05-31 14:45:06

标签: ruby email gem

我正在使用mail gem使用此代码发送带有UTF-8内容的电子邮件

Mail.defaults do
    ...
end

Mail.deliver do
    from    "user@example.com"
    to      "otheruser@example.com"
    subject "Mäbülö..."
    body    "Märchenbücher lösen Leseschwächen."
end

这样可行,但会发出警告

Non US-ASCII detected and no charset defined.
Defaulting to UTF-8, set your own if this is incorrect.

现在经过多次尝试,咨询邮件gem生成的文档以及源代码,我仍然无法设置charset。 Message.rb中有一个方法charset=,但当我添加对charset的调用时,如下所示:

Mail.deliver do
    from    "user@example.com"
    to      "otheruser@example.com"
    charset "UTF-8"
    subject "Mäbülö..."
    body    "Märchenbücher lösen Leseschwächen."
end

我得到了这个ArgumentError:

/usr/local/lib/ruby/gems/1.9.1/gems/mail-2.4.4/lib/mail/message.rb:1423:in `charset': wrong number of arguments (1 for 0) (ArgumentError)

如何在传递块中设置字符集?

3 个答案:

答案 0 :(得分:10)

mail.charset()返回当前的字符集,它不允许设置一个并且不接受任何参数。

为此,您需要使用mail.charset = ...

实际上可以在块中使用:

Mail.deliver do
  from    "user@example.com"
  to      "otheruser@example.com"
  subject "Mäbülö..."
  body    "Märchenbücher lösen Leseschwächen."
  charset = "UTF-8"
end

也可以没有阻止:

mail         = Mail.new
mail.charset = 'UTF-8'
mail.content_transfer_encoding = '8bit'

mail.from    = ...
mail.to      = ...
mail.subject = ...

mail.text_part do
  body ...
end

mail.html_part do
  content_type 'text/html; charset=UTF-8'
  body ...
end

mail.deliver!

答案 1 :(得分:3)

您还需要为各个部分设置编码。通过maxdec回答显示它。确保您也为text_part执行此操作。

这适合我。

mail = Mail.deliver do
  charset='UTF-8'
  content_transfer_encoding="8bit"

  require 'pry';binding.pry
  to      'xxx@xxx.yy'
  from    'yyy@yyy.ss'
  subject "Tet with äöüß"

  text_part do
    content_type "text/plain; charset=utf-8"
    body <<-EOF
       this is a test with äöüß
    EOF
  end
end

mail.deliver!

答案 2 :(得分:-3)

添加

# encoding: utf-8

在文件的开头。