From fcd352e0895c6020285ad46cb61a103d04c8a1ab Mon Sep 17 00:00:00 2001 From: Gerhard Schlager Date: Tue, 27 Mar 2018 18:28:37 +0200 Subject: [PATCH] FIX: Try fixing unparsable email addresses The mail gem returns `UnstructuredField` when it fails to parse email addresses, but the `Receiver` always expects an `AddressList`. --- lib/email/receiver.rb | 11 +++++++++++ spec/components/email/receiver_spec.rb | 8 ++++++++ spec/fixtures/emails/unparsable_email_addresses.eml | 7 +++++++ 3 files changed, 26 insertions(+) create mode 100644 spec/fixtures/emails/unparsable_email_addresses.eml diff --git a/lib/email/receiver.rb b/lib/email/receiver.rb index abf42f61e89..09c1d2540ac 100644 --- a/lib/email/receiver.rb +++ b/lib/email/receiver.rb @@ -64,6 +64,7 @@ module Email DistributedMutex.synchronize(@message_id) do begin return if IncomingEmail.exists?(message_id: @message_id) + ensure_valid_address_lists @from_email, @from_display_name = parse_from_field(@mail) @incoming_email = create_incoming_email process_internal @@ -77,6 +78,16 @@ module Email end end + def ensure_valid_address_lists + [:to, :cc, :bcc].each do |field| + addresses = @mail[field] + + if addresses&.errors.present? + @mail[field] = addresses.to_s.scan(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/i) + end + end + end + def is_blacklisted? return false if SiteSetting.ignore_by_title.blank? Regexp.new(SiteSetting.ignore_by_title, Regexp::IGNORECASE) =~ @mail.subject diff --git a/spec/components/email/receiver_spec.rb b/spec/components/email/receiver_spec.rb index 4c3a562f928..c8ba5ee0efa 100644 --- a/spec/components/email/receiver_spec.rb +++ b/spec/components/email/receiver_spec.rb @@ -886,4 +886,12 @@ describe Email::Receiver do end end end + + it "tries to fix unparsable email addresses in To, CC and BBC headers" do + expect { process(:unparsable_email_addresses) }.to raise_error(Email::Receiver::BadDestinationAddress) + + email = IncomingEmail.last + expect(email.to_addresses).to eq("foo@bar.com") + expect(email.cc_addresses).to eq("bob@example.com;carol@example.com") + end end diff --git a/spec/fixtures/emails/unparsable_email_addresses.eml b/spec/fixtures/emails/unparsable_email_addresses.eml new file mode 100644 index 00000000000..c94956d0554 --- /dev/null +++ b/spec/fixtures/emails/unparsable_email_addresses.eml @@ -0,0 +1,7 @@ +Date: 27 Mar 2018 11:51:04 +0200 +From: alice@example.com +To: foo@bar.com. +CC: bob@example.com., carol@example.com. +Subject: Email addresses ending with dot + +Lorem ipsum