diff --git a/lib/mail/body.rb b/lib/mail/body.rb index 2b24d297a..e9d08e4a5 100644 --- a/lib/mail/body.rb +++ b/lib/mail/body.rb @@ -162,7 +162,12 @@ def encoded(transfer_encoding = '8bit') else # Decode then encode to normalize and allow transforming # from base64 to Q-P and vice versa - enc.encode(dec.decode(raw_source)) + decoded = dec.decode(raw_source) + if defined?(Encoding) && charset && charset != "US-ASCII" + decoded.encode!(charset) + decoded.force_encoding('BINARY') unless Encoding.find(charset).ascii_compatible? + end + enc.encode(decoded) end end end diff --git a/lib/mail/fields/unstructured_field.rb b/lib/mail/fields/unstructured_field.rb index 5c2cb977f..2578cb213 100644 --- a/lib/mail/fields/unstructured_field.rb +++ b/lib/mail/fields/unstructured_field.rb @@ -166,6 +166,7 @@ def fold(prepend = 0) # :nodoc: end def encode(value) + value.encode!(charset) if defined?(Encoding) && charset (value.not_ascii_only? ? [value].pack("M").gsub("=\n", '') : value).gsub("\r", "=0D").gsub("\n", "=0A") end diff --git a/spec/mail/body_spec.rb b/spec/mail/body_spec.rb index 2ae27eb4e..4e7b1c720 100644 --- a/spec/mail/body_spec.rb +++ b/spec/mail/body_spec.rb @@ -382,4 +382,13 @@ body.should include('The') end end + + describe "non US-ASCII charset" do + it "should encoded" do + body = Mail::Body.new("あいうえお\n") + body.charset = 'iso-2022-jp' + expect = (RUBY_VERSION < '1.9') ? "あいうえお\r\n" : "\e$B$\"$$$&$($*\e(B\r\n" + body.encoded.should == expect + end + end end diff --git a/spec/mail/encodings_spec.rb b/spec/mail/encodings_spec.rb index 1eb30b715..01d7766ae 100644 --- a/spec/mail/encodings_spec.rb +++ b/spec/mail/encodings_spec.rb @@ -241,13 +241,12 @@ it "should round trip another complex string (koi-8)" do original = "Слово 9999 и число" + orginial = original.encode('koi8-r') if RUBY_VERSION >= "1.9" mail = Mail.new mail.subject = original mail[:subject].charset = 'koi8-r' wrapped = mail[:subject].wrapped_value unwrapped = Mail::Encodings.value_decode(wrapped) - orginial = original.force_encoding('koi8-r').encode!('utf-8') if RUBY_VERSION >= "1.9" - unwrapped.gsub("Subject: ", "").should == original end end diff --git a/spec/mail/fields/unstructured_field_spec.rb b/spec/mail/fields/unstructured_field_spec.rb index 5e943e286..48e39efb2 100644 --- a/spec/mail/fields/unstructured_field_spec.rb +++ b/spec/mail/fields/unstructured_field_spec.rb @@ -167,4 +167,10 @@ end end + describe "iso-2022-jp Subject" do + @field = Mail::UnstructuredField.new("Subject", "あいうえお") + @field.charset = 'iso-2022-jp' + expect = (RUBY_VERSION < '1.9') ? "Subject: =?ISO-2022-JP?Q?=E3=81=82=E3=81=84=E3=81=86=E3=81=88=E3=81=8A?=\r\n" : "Subject: =?ISO-2022-JP?Q?=1B$B$=22$$$&$=28$*=1B=28B?=\r\n" + @field.encoded.should == expect + end end