Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby mail gem - set charset in deliver block

Tags:

email

ruby

gem

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    "[email protected]"
    to      "[email protected]"
    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    "[email protected]"
    to      "[email protected]"
    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?

like image 378
gpinkas Avatar asked May 31 '13 14:05

gpinkas


1 Answers

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    "[email protected]"
  to      "[email protected]"
  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!
like image 89
maxdec Avatar answered Oct 03 '22 02:10

maxdec