diff --git a/lib/mail/header.rb b/lib/mail/header.rb index 34f62f4fb..80fab197a 100644 --- a/lib/mail/header.rb +++ b/lib/mail/header.rb @@ -195,7 +195,11 @@ def charset def charset=(val) params = self[:content_type].parameters rescue nil if params - params[:charset] = val + if val + params[:charset] = val + else + params.delete(:charset) + end end @charset = val end diff --git a/lib/mail/message.rb b/lib/mail/message.rb index b299d31fc..577d4f899 100644 --- a/lib/mail/message.rb +++ b/lib/mail/message.rb @@ -1489,7 +1489,9 @@ def add_charset warning = "Non US-ASCII detected and no charset defined.\nDefaulting to UTF-8, set your own if this is incorrect.\n" warn(warning) end - header[:content_type].parameters['charset'] = @charset + if @charset + header[:content_type].parameters['charset'] = @charset + end end end diff --git a/spec/mail/message_spec.rb b/spec/mail/message_spec.rb index 062b59333..12447cd53 100644 --- a/spec/mail/message_spec.rb +++ b/spec/mail/message_spec.rb @@ -1440,6 +1440,39 @@ def message_headers_should_match(message, other) expect(mail.parts.last.content_transfer_encoding).to match(/7bit|8bit|binary/) end + describe 'charset=' do + before do + @mail = Mail.new do + to 'mikel@test.lindsaar.net' + from 'bob@test.lindsaar.net' + subject 'Multipart email' + text_part do + body 'This is plain text' + end + html_part do + content_type 'text/html; charset=UTF-8' + body '

This is HTML

' + end + end + end + + it "should not add an empty charset header" do + @mail.charset = nil + + expect(@mail.multipart?).to eq true + expect(@mail.parts.count).to eq 2 + expect(@mail.encoded.scan(/charset=UTF-8/).count).to eq 2 + end + + it "should remove the charset header" do + @mail.charset = 'iso-8859-1' + @mail.charset = nil + + expect(@mail.encoded.scan(/charset=UTF-8/).count).to eq 2 + expect(@mail.encoded.scan(/charset=iso-8859-1/).count).to eq 0 + end + end + describe "content-transfer-encoding" do it "should use 7bit for only US-ASCII chars" do