From bf7add7a82610b9356443528feb6d2c1d14392f1 Mon Sep 17 00:00:00 2001 From: Bob Long Date: Mon, 20 Jan 2020 14:39:56 -0500 Subject: [PATCH] Handle incomptible encodings in email headers --- lib/mail/encodings.rb | 10 +++++++++- spec/mail/encoding_spec.rb | 7 +++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/lib/mail/encodings.rb b/lib/mail/encodings.rb index 35af804fa..773b0ec74 100644 --- a/lib/mail/encodings.rb +++ b/lib/mail/encodings.rb @@ -134,7 +134,15 @@ def Encodings.value_decode(str) when *Q_VALUES then q_value_decode(string) end end - end.join("") + end + + if lines.each_slice(2).all? { |x, y| Encoding.compatible?(x, y) } + lines.join("") + else + lines.map do |line| + line.encode("UTF-8", invalid: :replace, undef: :replace, replace: "�") + end.join("") + end end # Takes an encoded string of the format =??[QB]??= diff --git a/spec/mail/encoding_spec.rb b/spec/mail/encoding_spec.rb index ba395265b..800683434 100644 --- a/spec/mail/encoding_spec.rb +++ b/spec/mail/encoding_spec.rb @@ -189,6 +189,13 @@ expect(m.subject).to eq "Hello #{replace} World" end + it "should handle incompatible encodings by force encoding to UTF-8" do + m = Mail.new + subject = "\xEC =?utf-8?Q?=F0=9F=98=80?=".dup.force_encoding("ASCII-8BIT") + m['Subject'] = Mail::SubjectField.new(subject) + expect(m.subject).to eq "� 😀" + end + it "should replace characters of unknown and invalid encoding" do m = Mail.new m['Subject'] = Mail::SubjectField.new("Hello=?UNKNOWN?B?4g==?=")