Skip to content

Commit

Permalink
raise error when email address is invalid
Browse files Browse the repository at this point in the history
  • Loading branch information
i7an committed Dec 12, 2024
1 parent 12d5c97 commit a609393
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
15 changes: 14 additions & 1 deletion lib/mailtrap/mail.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@

require_relative 'mail/base'
require_relative 'mail/from_template'
require_relative 'errors'

module Mailtrap
module Mail
class << self
# @param message [Mail::Message]
# @return [Mailtrap::Mail::Base]
def from_message(message) # rubocop:disable Metrics/AbcSize, Metrics/MethodLength
Mailtrap::Mail::Base.new(
from: prepare_addresses(address_list(message['from'])&.addresses).first,
Expand Down Expand Up @@ -50,10 +53,19 @@ def from_message(message) # rubocop:disable Metrics/AbcSize, Metrics/MethodLengt

HEADERS_TO_REMOVE = (SPECIAL_HEADERS + ACTIONMAILER_ADDED_HEADERS).freeze

# @param header [Mail::Field, nil]
# @return [Mail::AddressList, nil]
def address_list(header)
header.respond_to?(:element) ? header.element : header&.address_list
return nil unless header

unless header.errors.empty?
raise Mailtrap::Error, ["failed to parse '#{header.name}': '#{header.unparsed_value}'"]
end

header.respond_to?(:element) ? header.element : header.address_list
end

# @param addresses [Array<Mail::Address>, nil]
def prepare_addresses(addresses)
Array(addresses).map { |address| prepare_address(address) }
end
Expand All @@ -66,6 +78,7 @@ def prepare_headers(message)
.compact
end

# @param address [Mail::Address]
def prepare_address(address)
{
email: address.address,
Expand Down
13 changes: 13 additions & 0 deletions spec/mailtrap/mail_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -142,5 +142,18 @@
# (There will be a "'from' is required" error from the server)
its(:from) { is_expected.to be_nil }
end

%i[from to cc bcc].each do |header|
context "when '#{header}' is invalid" do
let(:message_params) { super().merge(header => 'invalid [email protected]') }

it 'raises an error' do
expect { mail }.to raise_error(
Mailtrap::Error,
"failed to parse '#{header.capitalize}': 'invalid [email protected]'"
)
end
end
end
end
end

0 comments on commit a609393

Please sign in to comment.