简体   繁体   中英

ruby mail gem - set charset in deliver block

I'm using the mail gem to send E-Mail with UTF-8 content using this code

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

This works, but gives the warning

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

Now after much trying around, consulting mail gem's generated documentation as well as source code, I'm still unable to set the charset. There is a method charset= in Message.rb, but when I add a call to charset, like so:

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

I get this 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)

How can I set the charset within the deliver block?

mail.charset() returns the current charset, it does not allow to set one and does not take any argument.

To do so you need to use mail.charset = ...

It's actually possible inside the block with:

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

It's also possible without a block:

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!

you need to set the encoding also for the individual parts. Answer by maxdec shows it. Ensure that you do this for the text_part also.

This works for me.

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!

I use mail (2.7.1), neither charset nor content_transfer_encoding work for me.

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

The following works for me!

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

Add

# encoding: utf-8

at the beginning of file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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