Skip to content

Commit fcb5de9

Browse files
committed
Handle unknown b-value encoding
by treating it as ascii as well as ignoring any invalid chars
1 parent a6cddd0 commit fcb5de9

File tree

3 files changed

+19
-2
lines changed

3 files changed

+19
-2
lines changed

lib/mail/version_specific/ruby_1_8.rb

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,18 @@ def Ruby18.get_constant(klass, string)
5656
end
5757

5858
def Ruby18.transcode_charset(str, from_encoding, to_encoding = 'UTF-8')
59-
Iconv.conv("#{normalize_iconv_charset_encoding(to_encoding)}//IGNORE", normalize_iconv_charset_encoding(from_encoding), str)
59+
retried = false
60+
begin
61+
Iconv.conv("#{normalize_iconv_charset_encoding(to_encoding)}//IGNORE", normalize_iconv_charset_encoding(from_encoding), str)
62+
rescue Iconv::InvalidEncoding
63+
if retried
64+
raise
65+
else
66+
from_encoding = 'ASCII'
67+
retried = true
68+
retry
69+
end
70+
end
6071
end
6172

6273
def Ruby18.b_value_encode(str, encoding)

lib/mail/version_specific/ruby_1_9.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ def Ruby19.b_value_decode(str)
9090
str = Ruby19.decode_base64(match[2])
9191
str = charset_encoder.encode(str, charset)
9292
end
93-
decoded = str.encode(Encoding::UTF_8, :invalid => :replace, :replace => "")
93+
decoded = str.encode(Encoding::UTF_8, :undef => :replace, :invalid => :replace, :replace => "")
9494
decoded.valid_encoding? ? decoded : decoded.encode(Encoding::UTF_16LE, :invalid => :replace, :replace => "").encode(Encoding::UTF_8)
9595
rescue Encoding::UndefinedConversionError, ArgumentError, Encoding::ConverterNotFoundError
9696
warn "Encoding conversion failed #{$!}"

spec/mail/encoding_spec.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,12 @@
196196
end
197197
end
198198

199+
it "should skip characters of unknown and invalid encoding" do
200+
m = Mail.new
201+
m['Subject'] = Mail::SubjectField.new("Hello=?UNKNOWN?B?4g==?=")
202+
expect(m.subject).to eq "Hello"
203+
end
204+
199205
if RUBY_VERSION > '1.9'
200206
describe "#pick_encoding" do
201207
it "picks binary for nil" do

0 commit comments

Comments
 (0)