5

我正在使用邮件 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 生成的文档以及源代码,我仍然无法设置字符集。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)

如何在交付块中设置字符集?

4

3 回答 3

11

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!
于 2013-06-11T09:26:03.970 回答
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!
于 2013-07-27T11:41:35.837 回答
0

我使用邮件(2.7.1),既不适合我,charset也不content_transfer_encoding适合我。

charset='UTF-8'
content_transfer_encoding="8bit"

以下对我有用!

content_type "text/plain; charset=utf-8"
于 2021-05-21T02:15:53.220 回答