繁体   English   中英

ruby mail gem - 在交付块中设置字符集

[英]ruby mail gem - set charset in deliver block

我正在使用邮件 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)

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

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!

您还需要为各个部分设置编码。 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.7.1), charsetcontent_transfer_encoding都不适合我。

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

以下对我有用!

content_type "text/plain; charset=utf-8"

添加

# encoding: utf-8

在文件的开头。

暂无
暂无

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

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