Skip to content

Commit

Permalink
MT-12537: remove extraneous headers added by ActionMailer
Browse files Browse the repository at this point in the history
  • Loading branch information
leonid-shevtsov committed Jul 5, 2024
1 parent 84b0867 commit 61a504f
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
17 changes: 15 additions & 2 deletions lib/mailtrap/sending/convert.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def from_message(message) # rubocop:disable Metrics/AbcSize, Metrics/MethodLengt

private

PROCESSED_HEADERS = %w[
SPECIAL_HEADERS = %w[
from
to
cc
Expand All @@ -35,14 +35,27 @@ def from_message(message) # rubocop:disable Metrics/AbcSize, Metrics/MethodLengt
contenttype
].freeze

# ActionMailer adds these headers my calling `Mail::Message#encoded`,
# as if the message is to be delivered via SMTP.
# Since the message will actually be generated on the Mailtrap side from its components,
# the headers are redundant and potentially conflicting, so we remove them.
ACTIONMAILER_ADDED_HEADERS = %w[
contenttransferencoding
date
messageid
mimeversion
]

HEADERS_TO_REMOVE = SPECIAL_HEADERS+ACTIONMAILER_ADDED_HEADERS

def prepare_addresses(addresses)
Array(addresses).map { |address| prepare_address(address) }
end

def prepare_headers(message)
message
.header_fields
.reject { |header| PROCESSED_HEADERS.include?(header.name.downcase.delete('-')) }
.reject { |header| HEADERS_TO_REMOVE.include?(header.name.downcase.delete('-')) }
.to_h { |header| [header.name, header.value] }
.compact
end
Expand Down
10 changes: 7 additions & 3 deletions spec/mailtrap/sending/convert_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
RSpec.describe Mailtrap::Sending::Convert do
describe '.from_message' do
subject(:mail) do
# This method is called by ActionMailer before passing the message to delivery,
# and populates some redundant headers on the message.
# We want to ensure they are removed.
message.encoded
described_class.from_message(message)
end

Expand Down Expand Up @@ -97,7 +101,7 @@
message.text_part = 'Some text'
end

it 'only text is present' do
specify 'only text is present' do
expect(mail.text).to eq('Some text')
expect(mail.html).to be_nil
end
Expand All @@ -108,7 +112,7 @@
message.html_part = '<div>HTML part</div>'
end

it 'only html is present' do
specify 'only html is present' do
expect(mail.text).to be_nil
expect(mail.html).to eq('<div>HTML part</div>')
end
Expand All @@ -120,7 +124,7 @@
message.html_part = '<div>HTML part</div>'
end

it 'only html is present' do
specify 'both parts are present' do
expect(mail.text).to eq('Some text')
expect(mail.html).to eq('<div>HTML part</div>')
end
Expand Down

0 comments on commit 61a504f

Please sign in to comment.