# Copyright (C) 2012-2026 Zammad Foundation, https://zammad-foundation.org/

require 'rails_helper'

RSpec.describe Channel::EmailParser, type: :model do
  describe '#parse' do

    shared_examples 'parses email correctly' do |stored_email|
      context "for #{stored_email}" do
        let(:yml_file)   { stored_email.sub_ext('.yml') }
        let(:content)    { YAML.load_file(yml_file, permitted_classes: [ActiveSupport::HashWithIndifferentAccess]) }
        let(:parsed)     { described_class.new.parse(File.read(stored_email)) }
        let(:parsed_msg) { parsed.slice(*content.keys) }

        it 'parses correctly' do
          expect(File).to exist(yml_file)
          expect(parsed_msg).to eq(content)
        end
      end
    end

    describe 'when mail does not contain any sender specification' do
      subject(:instance) { described_class.new }

      let(:raw_mail) { <<~RAW.chomp }
        To: baz@qux.net
        Subject: Foo

        Lorem ipsum dolor
      RAW

      it 'raises error even if exception is false' do
        expect { described_class.new.parse(raw_mail) }
          .to raise_error(Exceptions::MissingAttribute, 'Could not parse any sender attribute from the email. Checked fields: From, Reply-To, Return-Path, Sender')
      end
    end

    describe 'when mail does not contain any sender specification with disabled missing attribute exceptions' do
      subject(:instance) { described_class.new }

      let(:raw_mail) { <<~RAW.chomp }
        To: baz@qux.net
        Subject: Foo

        Lorem ipsum dolor
      RAW

      it 'prevents raising an error' do
        expect { described_class.new.parse(raw_mail, allow_missing_attribute_exceptions: false) }
          .not_to raise_error
      end
    end

    # https://github.com/zammad/zammad/issues/5905
    describe 'when mail does not declare a content type' do
      subject(:parsed) { described_class.new.parse(raw_mail) }

      let(:raw_mail) { <<~RAW.chomp }
        Date: Mon, 15 Dec 2025 21:49:11 +0100
        To: support@test.local
        From: user6@example.com
        Subject: Ticket #6
        Message-Id: <20251215214911.090380@macbookpro.fritz.box>
        X-Mailer: swaks v20240103.0 jetmore.org/john/code/swaks/

        This is test email 6
      RAW

      it 'parses the body without treating it as an attachment' do
        expect(parsed[:attachments]).to be_empty
        expect(parsed[:body].strip).to eq('This is test email 6')
      end
    end

    # To write new .yml files for emails you can use the following rake task:
    #
    # rake zammad:email_parser:debug:generate_yml[/path/to/your/email.box]
    #
    # To renew all existing files, you can use the following rake task:
    #
    # rake zammad:email_parser:debug:regenerate_all_ymls
    #
    context 'when checking a bunch of stored emails for correct parsing behaviour' do
      Rails.root.glob('test/data/mail/mail*.box').each do |stored_email|
        if ENV['MAIL_PARSER_TEST'] && stored_email.to_s.exclude?("#{ENV['MAIL_PARSER_TEST']}.box")
          next
        end

        include_examples('parses email correctly', stored_email)
      end

      it 'ensures tests were dynamically generated' do
        expect(Rails.root.glob('test/data/mail/mail*.box').count).to eq(121)
      end
    end

    # regression test for issue 2390 - Add a postmaster filter to not show emails with potential issue
    describe 'handling HTML links in message content' do
      context 'with under 5,000 links' do
        it 'parses message content as normal' do
          expect(described_class.new.parse(<<~RAW)[:body]).to start_with('<a href="https://zammad.com/"')
            From: nicole.braun@zammad.com
            Content-Type: text/html

            <html><body>
            #{Array.new(10) { '<a href="https://zammad.com/">Dummy Link</a>' }.join(' ')}
            </body></html>
          RAW
        end
      end

      context 'with 5,000+ links' do
        it 'replaces message content with error message' do
          expect(described_class.new.parse(<<~RAW)).to include('body' => Channel::EmailParser::EXCESSIVE_LINKS_MSG)
            From: nicole.braun@zammad.com
            Content-Type: text/html

            <html><body>
            #{Array.new(5001) { '<a href="https://zammad.com/">Dummy Link</a>' }.join(' ')}
            </body></html>
          RAW
        end
      end
    end

    describe 'handling Japanese email in ISO-2022-JP encoding' do
      let(:mail_file) { Rails.root.join('test/data/mail/mail091.box') }
      let(:raw_mail)  { File.read(mail_file) }
      let(:parsed)    { described_class.new.parse(raw_mail) }

      it { expect(parsed['body']).to eq '<div>このアドレスへのメルマガを解除してください。</div>' }
      it { expect(parsed['subject']).to eq 'メルマガ解除' }
    end

    # regression test for issue 6340 - Mail body silently falls back to CharDet
    #   when Encoding.find cannot resolve the declared charset label
    describe 'handling a charset label that Ruby cannot resolve' do
      let(:mail_file) { Rails.root.join('test/data/mail/mail119.box') }
      let(:raw_mail)  { File.read(mail_file) }
      let(:parsed)    { described_class.new.parse(raw_mail) }

      it { expect(parsed['body']).to start_with '<p>Добрый день!</p>' }
    end

    describe 'handling RFC 2047 encoded-words in From addr-spec (security)' do
      let(:group)   { create(:group) }
      let(:channel) { create(:email_channel, group: group) }
      let(:agent)   { create(:agent, email: 'agent@victim.example', groups: [group]) }

      before do
        Setting.set('postmaster_sender_is_agent_search_for_customer', false)
        agent && channel
        Trigger.destroy_all
      end

      context 'with multi-segment Q-encoded ladder' do
        let(:raw_mail) do
          <<~RAW
            From: =?utf-8?Q?attacker?Q?agent?=@victim.example
            To: support@example.test
            Subject: test

            body
          RAW
        end

        it 'does not set article sender to Agent' do
          described_class.new.process(channel, raw_mail)
          expect(Ticket::Article.last.sender.name).not_to eq('Agent')
        end
      end

      context 'with multi-segment B-encoded ladder' do
        let(:raw_mail) do
          <<~RAW
            From: =?utf-8?B?YXR0YWNrZXI=?B?YWdlbnQ=?=@victim.example
            To: support@example.test
            Subject: test

            body
          RAW
        end

        it 'does not set article sender to Agent' do
          described_class.new.process(channel, raw_mail)
          expect(Ticket::Article.last.sender.name).not_to eq('Agent')
        end
      end

      context 'with valid clear-text From address' do
        let(:raw_mail) do
          <<~RAW
            From: agent@victim.example
            To: support@example.test
            Subject: test

            body
          RAW
        end

        it 'still sets article sender to Agent' do
          described_class.new.process(channel, raw_mail)
          expect(Ticket::Article.last.sender.name).to eq('Agent')
        end
      end

      context 'with encoded-word in display name only' do
        let(:raw_mail) do
          <<~RAW
            From: =?utf-8?Q?Some+Name?= <agent@victim.example>
            To: support@example.test
            Subject: test

            body
          RAW
        end

        it 'still sets article sender to Agent' do
          described_class.new.process(channel, raw_mail)
          expect(Ticket::Article.last.sender.name).to eq('Agent')
        end
      end

      context 'with single QP encoded-word' do
        let(:raw_mail) do
          <<~RAW
            From: =?utf-8?Q?agent=40victim.example?=
            To: support@example.test
            Subject: test

            body
          RAW
        end

        it 'still sets article sender to Agent' do
          described_class.new.process(channel, raw_mail)
          expect(Ticket::Article.last.sender.name).to eq('Agent')
        end
      end

    end

    describe "invalid 'Resent-Date' header field" do
      it 'is ignored' do
        expect(described_class.new.parse(<<~RAW)['resent_date']).to be_nil
          From: me@example.com
          To: to@example.com
          Subject: 123
          Resent-Date: 6/29/2022 11:57:13 AM

          body 123
        RAW
      end
    end

    describe 'inline attachment' do
      let(:cid)   { '485376C9-2486-4351-B932-E2010998F579@home' }
      let(:html)  { "test <img src='cid:#{cid}'>" }
      let(:store) { create(:store, :image, preferences: store_preferences) }

      let(:store_preferences) do
        {
          'Content-ID':   cid,
          'Mime-Type':    'image/jpg',
          'Content-Type': 'application/others; name=inline_image.jpg'
        }
      end

      it 'gets Content-ID' do
        mail = Channel::EmailBuild.build(
          from:         'sender@example.com',
          to:           'recipient@example.com',
          body:         html,
          content_type: 'text/html',
          attachments:  [ store ],
        )

        parser = described_class.new
        data = parser.parse(mail.to_s)

        inline_image_attachment = data[:attachments].last

        expect(inline_image_attachment[:preferences]['Content-ID']).to eq cid
      end
    end

    describe 'calendar attachment without a filename' do
      let(:store) { create(:store, :ics).tap { |store| store.filename = '' } }

      it 'gets fallback filename with correct file extension (#5427)' do
        mail = Channel::EmailBuild.build(
          from:         'sender@example.com',
          to:           'recipient@example.com',
          body:         'foobar',
          content_type: 'text/html',
          attachments:  [store],
        )

        parser = described_class.new
        data = parser.parse(mail.to_s)

        calendar_attachment = data[:attachments].last

        expect(calendar_attachment[:filename]).to eq('calendar.ics')
      end
    end
  end

  describe '#process' do
    let(:raw_mail) { File.read(mail_file) }

    before { Trigger.destroy_all } # triggers may cause additional articles to be created

    describe 'auto-creating new users' do
      context 'with one unrecognized email address' do
        it 'creates one new user' do
          expect { described_class.new.process({}, <<~RAW) }.to change(User, :count).by(1)
            From: #{Faker::Internet.unique.email}
          RAW
        end
      end

      context 'with a large number of unrecognized recipient addresses' do
        it 'never creates more than 40 users' do
          expect { described_class.new.process({}, <<~RAW) }.to change(User, :count).by(40)
            From: nicole.braun@zammad.org
            To: #{Array.new(20) { Faker::Internet.unique.email }.join(', ')}
            Cc: #{Array.new(21) { Faker::Internet.unique.email }.join(', ')}
          RAW
        end
      end

      context 'with two unrecognizded email addresses with international domain name' do
        it 'create new user email unicode characters', :aggregate_failures do
          expect { described_class.new.process({}, <<~RAW) }.to change(User, :count).by(2)
            From: john.doe@xn--cme-pla.corp
            To: jane.doe@xn--cme-pla.corp
          RAW
          expect(User).to exist(login: 'john.doe@äcme.corp')
            .and(exist(email: 'jane.doe@äcme.corp'))
        end
      end

      context 'with existing system email address' do
        let!(:email_address) { create(:email_address, email: 'baz@qux.net', channel: nil) }
        let!(:group)         { create(:group, name: 'baz headquarter', email_address: email_address) }
        let!(:channel) do
          channel = create(:email_channel, group: group)
          email_address.update(channel: channel)
          channel
        end

        it 'creates no new user for system mail adress in cc' do
          expect { described_class.new.process({}, <<~RAW) }.to change(User, :count).by(1)
            From: nicole.braun@zammad.org
            To: #{email_address.email}
            Cc: #{email_address.email}, #{Faker::Internet.unique.email}
          RAW
        end
      end
    end

    describe 'auto-updating existing users' do
      context 'with a previous email with no real name in the From: header' do
        let!(:customer) { described_class.new.process({}, previous_email).first.customer }

        let(:previous_email) { <<~RAW.chomp }
          From: customer@example.com
          To: myzammad@example.com
          Subject: test sender name update 1

          Some Text
        RAW

        context 'and a new email with a real name in the From: header' do
          let(:new_email) { <<~RAW.chomp }
            From: Max Smith <customer@example.com>
            To: myzammad@example.com
            Subject: test sender name update 2

            Some Text
          RAW

          it 'updates the customer’s #firstname and #lastname' do
            expect { described_class.new.process({}, new_email) }
              .to change { customer.reload.firstname }.from('').to('Max')
              .and change { customer.reload.lastname }.from('').to('Smith')
          end
        end
      end

      describe 'handle database failures' do
        subject(:instance) { described_class.new }

        let(:mail_data) { attributes_for(:failed_email)[:data] }

        before do
          allow(instance).to receive(:process_with_timeout).and_raise('error')
          allow_any_instance_of(Ticket).to receive(:valid?).and_return(false)
        end

        it 'raises when the error ticket cannot be created either' do
          expect { instance.process({}, mail_data) }
            .to raise_error(ActiveRecord::ActiveRecordError)
        end
      end
    end

    describe 'creating new tickets' do
      context 'when subject contains no ticket reference' do
        let(:raw_mail) { <<~RAW.chomp }
          From: foo@bar.com
          To: baz@qux.net
          Subject: Foo

          Lorem ipsum dolor
        RAW

        it 'creates a ticket and article' do
          expect { described_class.new.process({}, raw_mail) }
            .to change(Ticket, :count).by(1)
            .and change(Ticket::Article, :count).by_at_least(1)
        end

        it 'sets #title to email subject' do
          described_class.new.process({}, raw_mail)

          expect(Ticket.last.title).to eq('Foo')
        end

        it 'sets #state to "new"' do
          described_class.new.process({}, raw_mail)

          expect(Ticket.last.state.name).to eq('new')
        end

        context 'when no channel is given but a group with the :to address exists' do
          let!(:email_address) { create(:email_address, email: 'baz@qux.net', channel: nil) }
          let!(:group)         { create(:group, name: 'baz headquarter', email_address: email_address) }
          let!(:channel) do
            channel = create(:email_channel, group: group)
            email_address.update(channel: channel)
            channel
          end

          it 'sets the group based on the :to field' do
            described_class.new.process({}, raw_mail)
            expect(Ticket.last.group.id).to eq(group.id)
          end
        end

        context 'when from address matches an existing agent' do
          before do
            Setting.set('postmaster_sender_is_agent_search_for_customer', search_for_customer)
          end

          describe 'postmaster filter group routing' do
            let(:channel) { create(:email_channel, group: initial_group) }
            let(:agent)               { create(:agent_and_customer, email: 'foo@bar.com', groups: [agent_group]) }
            let(:initial_group)       { create(:group) }
            let(:routed_group)        { create(:group) }
            let(:postmaster_filter)   { create(:postmaster_filter, :route_to_group, group: routed_group) }
            let(:search_for_customer) { false }

            before { agent && postmaster_filter }

            context 'when agent-customer is customer in target group but postmaster filter routes to another group' do
              let(:agent_group) { routed_group }

              it 'sets article.sender to "Agent"' do
                described_class.new.process(channel, raw_mail)

                expect(Ticket::Article.last.sender.name).to eq('Agent')
              end
            end

            context 'when agent-customer is agent in target group but postmaster filter routes to another group' do
              let(:agent_group) { initial_group }

              it 'sets article.sender to "Agent"' do
                described_class.new.process(channel, raw_mail)

                expect(Ticket::Article.last.sender.name).to eq('Customer')
              end
            end
          end

          context 'when agent is agent in target group' do
            let!(:agent) { create(:agent, email: 'foo@bar.com', groups: Group.all) }

            context 'when search for customer is false' do
              let(:search_for_customer) { false }

              it 'sets article.sender to "Agent"' do
                described_class.new.process({}, raw_mail)

                expect(Ticket::Article.last.sender.name).to eq('Agent')
              end

              it 'sets ticket.state to "new"' do
                described_class.new.process({}, raw_mail)

                expect(Ticket.last.state.name).to eq('new')
              end

              it 'sets agent as customer' do
                described_class.new.process({}, raw_mail)

                expect(Ticket.last.customer).to eq(agent)
              end
            end

            context 'when search for customer is true' do
              let(:search_for_customer) { true }

              it 'sets article.sender to "Agent"' do
                described_class.new.process({}, raw_mail)

                expect(Ticket::Article.last.sender.name).to eq('Agent')
              end

              it 'sets ticket.state to "new"' do
                described_class.new.process({}, raw_mail)

                expect(Ticket.last.state.name).to eq('new')
              end

              it 'sets customer using TO value' do
                described_class.new.process({}, raw_mail)

                expect(Ticket.last.customer).to have_attributes(email: 'baz@qux.net')
              end
            end
          end

          context 'when agent is customer in target group' do
            let!(:agent) { create(:agent, email: 'foo@bar.com') }

            context 'when search for customer is false' do
              let(:search_for_customer) { false }

              it 'sets article.sender to "Agent"' do
                described_class.new.process({}, raw_mail)

                expect(Ticket::Article.last.sender.name).to eq('Customer')
              end

              it 'sets ticket.state to "new"' do
                described_class.new.process({}, raw_mail)

                expect(Ticket.last.state.name).to eq('new')
              end

              it 'sets agent as customer' do
                described_class.new.process({}, raw_mail)

                expect(Ticket.last.customer).to eq(agent)
              end
            end

            context 'when search for customer is true' do
              let(:search_for_customer) { true }

              it 'sets article.sender to "Agent"' do
                described_class.new.process({}, raw_mail)

                expect(Ticket::Article.last.sender.name).to eq('Customer')
              end

              it 'sets ticket.state to "new"' do
                described_class.new.process({}, raw_mail)

                expect(Ticket.last.state.name).to eq('new')
              end

              it 'sets customer using TO value' do
                described_class.new.process({}, raw_mail)

                expect(Ticket.last.customer).to have_attributes(email: 'baz@qux.net')
              end
            end
          end
        end

        context 'when from address matches an existing agent customer' do
          let!(:agent_customer) { create(:agent_and_customer, email: 'foo@bar.com') }
          let!(:ticket)         { create(:ticket, customer: agent_customer) }
          let!(:raw_email)      { <<~RAW.chomp }
            From: foo@bar.com
            To: myzammad@example.com
            Subject: [#{Setting.get('ticket_hook') + Setting.get('ticket_hook_divider') + ticket.number}] test

            Lorem ipsum dolor
          RAW

          it 'sets article.sender to "Customer"' do
            described_class.new.process({}, raw_email)

            expect(Ticket::Article.last.sender.name).to eq('Customer')
          end
        end

        context 'when reply-to is taken as sender/from of email' do
          let(:reply_to) { 'jane.doe@example.corp' }
          let(:raw_mail) { <<~RAW.chomp }
            From: foo@bar.com
            To: baz@qux.net
            Reply-To: #{reply_to}
            Subject: Foo

            Lorem ipsum dolor
          RAW

          before do
            Setting.set('postmaster_sender_based_on_reply_to', 'as_sender_of_email')
          end

          it 'sets reply-to as from value' do
            described_class.new.process({}, raw_mail)

            expect(Ticket.last.articles.reload.first.from).to eq('jane.doe@example.corp')
          end

          context 'with broken reply-to value' do
            let(:reply_to) { '<Jane Doe>' }

            it 'ignores reply-to and keeps from' do
              described_class.new.process({}, raw_mail)

              expect(Ticket.last.articles.reload.first.from).to eq('foo@bar.com')
            end
          end
        end

        context 'when from address matches an existing customer' do
          let!(:customer) { create(:customer, email: 'foo@bar.com') }

          it 'sets article.sender to "Customer"' do
            described_class.new.process({}, raw_mail)

            expect(Ticket.last.articles.reload.first.sender.name).to eq('Customer')
          end

          it 'sets ticket.state to "new"' do
            described_class.new.process({}, raw_mail)

            expect(Ticket.last.state.name).to eq('new')
          end
        end

        context 'when from address is unrecognized' do
          it 'sets article.sender to "Customer"' do
            described_class.new.process({}, raw_mail)

            expect(Ticket.last.articles.reload.first.sender.name).to eq('Customer')
          end
        end
      end

      context 'when email contains x-headers' do
        let(:raw_mail) { <<~RAW.chomp }
          From: foo@bar.com
          To: baz@qux.net
          Subject: Foo
          X-Zammad-Ticket-priority: 3 high

          Lorem ipsum dolor
        RAW

        context 'when channel is not trusted' do
          let(:channel) { create(:channel, options: { inbound: { trusted: false } }) }

          it 'does not change the priority of the ticket (no channel)' do
            described_class.new.process({}, raw_mail)

            expect(Ticket.last.priority.name).to eq('2 normal')
          end

          it 'does not change the priority of the ticket (untrusted)' do
            described_class.new.process(channel, raw_mail)

            expect(Ticket.last.priority.name).to eq('2 normal')
          end
        end

        context 'when channel is trusted' do
          let(:channel) { create(:channel, options: { inbound: { trusted: true } }) }

          it 'does not change the priority of the ticket' do
            described_class.new.process(channel, raw_mail)

            expect(Ticket.last.priority.name).to eq('3 high')
          end
        end
      end

      context 'Mentions:' do
        let(:agent)    { create(:agent) }
        let(:raw_mail) { <<~RAW.chomp }
          From: foo@bar.com
          To: baz@qux.net
          Subject: Foo

          Lorem ipsum dolor <a data-mention-user-id="#{agent.id}">agent</a>
        RAW

        it 'creates a ticket and article without mentions and no exception raised' do
          expect { described_class.new.process({}, raw_mail) }
            .to change(Ticket, :count).by(1)
            .and change(Ticket::Article, :count).by_at_least(1)
            .and not_change(Mention, :count)
        end
      end
    end

    describe 'associating emails to existing tickets' do
      let!(:ticket) { create(:ticket) }
      let(:ticket_ref) { Setting.get('ticket_hook') + Setting.get('ticket_hook_divider') + ticket.number }

      describe 'based on where a ticket reference appears in the message' do
        shared_context 'ticket reference in subject' do
          let(:raw_mail) { <<~RAW.chomp }
            From: me@example.com
            To: customer@example.com
            Subject: #{ticket_ref}

            Lorem ipsum dolor
          RAW
        end

        shared_context 'ticket reference in body' do
          let(:raw_mail) { <<~RAW.chomp }
            From: me@example.com
            To: customer@example.com
            Subject: no reference

            Lorem ipsum dolor #{ticket_ref}
          RAW
        end

        shared_context 'ticket reference in body (text/html)' do
          let(:raw_mail) { <<~RAW.chomp }
            From: me@example.com
            To: customer@example.com
            Subject: no reference
            Content-Transfer-Encoding: 7bit
            Content-Type: text/html;

            <b>Lorem ipsum dolor #{ticket_ref}</b>
          RAW
        end

        shared_context 'ticket reference in text/plain attachment' do
          let(:raw_mail) { <<~RAW.chomp }
            From: me@example.com
            Content-Type: multipart/mixed; boundary="Apple-Mail=_ED77AC8D-FB6F-40E5-8FBE-D41FF5E1BAF2"
            Subject: no reference
            Date: Sun, 30 Aug 2015 23:20:54 +0200
            To: Martin Edenhofer <me@zammad.com>
            Mime-Version: 1.0 (Mac OS X Mail 8.2 (2104))
            X-Mailer: Apple Mail (2.2104)


            --Apple-Mail=_ED77AC8D-FB6F-40E5-8FBE-D41FF5E1BAF2
            Content-Transfer-Encoding: 7bit
            Content-Type: text/plain;
              charset=us-ascii

            no reference
            --Apple-Mail=_ED77AC8D-FB6F-40E5-8FBE-D41FF5E1BAF2
            Content-Disposition: attachment;
              filename=test1.txt
            Content-Type: text/plain;
              name="test.txt"
            Content-Transfer-Encoding: 7bit

            Some Text #{ticket_ref}

            --Apple-Mail=_ED77AC8D-FB6F-40E5-8FBE-D41FF5E1BAF2--
          RAW
        end

        shared_context 'ticket reference in text/html (as content) attachment' do
          let(:raw_mail) { <<~RAW.chomp }
            From: me@example.com
            Content-Type: multipart/mixed; boundary="Apple-Mail=_ED77AC8D-FB6F-40E5-8FBE-D41FF5E1BAF2"
            Subject: no reference
            Date: Sun, 30 Aug 2015 23:20:54 +0200
            To: Martin Edenhofer <me@zammad.com>
            Mime-Version: 1.0 (Mac OS X Mail 8.2 (2104))
            X-Mailer: Apple Mail (2.2104)


            --Apple-Mail=_ED77AC8D-FB6F-40E5-8FBE-D41FF5E1BAF2
            Content-Transfer-Encoding: 7bit
            Content-Type: text/plain;
              charset=us-ascii

            no reference
            --Apple-Mail=_ED77AC8D-FB6F-40E5-8FBE-D41FF5E1BAF2
            Content-Disposition: attachment;
              filename=test1.txt
            Content-Type: text/html;
              name="test.txt"
            Content-Transfer-Encoding: 7bit

            <div>Some Text #{ticket_ref}</div>

            --Apple-Mail=_ED77AC8D-FB6F-40E5-8FBE-D41FF5E1BAF2--
          RAW
        end

        shared_context 'ticket reference in text/html (attribute) attachment' do
          let(:raw_mail) { <<~RAW.chomp }
            From: me@example.com
            Content-Type: multipart/mixed; boundary="Apple-Mail=_ED77AC8D-FB6F-40E5-8FBE-D41FF5E1BAF2"
            Subject: no reference
            Date: Sun, 30 Aug 2015 23:20:54 +0200
            To: Martin Edenhofer <me@zammad.com>
            Mime-Version: 1.0 (Mac OS X Mail 8.2 (2104))
            X-Mailer: Apple Mail (2.2104)


            --Apple-Mail=_ED77AC8D-FB6F-40E5-8FBE-D41FF5E1BAF2
            Content-Transfer-Encoding: 7bit
            Content-Type: text/plain;
              charset=us-ascii

            no reference
            --Apple-Mail=_ED77AC8D-FB6F-40E5-8FBE-D41FF5E1BAF2
            Content-Disposition: attachment;
              filename=test1.txt
            Content-Type: text/html;
              name="test.txt"
            Content-Transfer-Encoding: 7bit

            <div>Some Text <b data-something="#{ticket_ref}">some text</b></div>

            --Apple-Mail=_ED77AC8D-FB6F-40E5-8FBE-D41FF5E1BAF2--
          RAW
        end

        shared_context 'ticket reference in image/jpg attachment' do
          let(:raw_mail) { <<~RAW.chomp }
            From: me@example.com
            Content-Type: multipart/mixed; boundary="Apple-Mail=_ED77AC8D-FB6F-40E5-8FBE-D41FF5E1BAF2"
            Subject: no reference
            Date: Sun, 30 Aug 2015 23:20:54 +0200
            To: Martin Edenhofer <me@zammad.com>
            Mime-Version: 1.0 (Mac OS X Mail 8.2 (2104))
            X-Mailer: Apple Mail (2.2104)


            --Apple-Mail=_ED77AC8D-FB6F-40E5-8FBE-D41FF5E1BAF2
            Content-Transfer-Encoding: 7bit
            Content-Type: text/plain;
              charset=us-ascii

            no reference
            --Apple-Mail=_ED77AC8D-FB6F-40E5-8FBE-D41FF5E1BAF2
            Content-Disposition: attachment;
              filename=test1.jpg
            Content-Type: image/jpg;
              name="test.jpg"
            Content-Transfer-Encoding: 7bit

            Some Text #{ticket_ref}

            --Apple-Mail=_ED77AC8D-FB6F-40E5-8FBE-D41FF5E1BAF2--
          RAW
        end

        shared_context 'ticket reference in In-Reply-To header' do
          let(:raw_mail) { <<~RAW.chomp }
            From: me@example.com
            To: customer@example.com
            Subject: no reference
            In-Reply-To: #{article.message_id}

            Lorem ipsum dolor
          RAW

          let!(:article) { create(:ticket_article, ticket: ticket, message_id: '<20150830145601.30.608882@edenhofer.zammad.com>') }
        end

        shared_context 'ticket reference in References header' do
          let(:raw_mail) { <<~RAW.chomp }
            From: me@example.com
            To: customer@example.com
            Subject: no reference
            References: <DA918CD1-BE9A-4262-ACF6-5001E59291B6@zammad.com> #{article.message_id} <DA918CD1-BE9A-4262-ACF6-5001E59291XX@zammad.com>

            Lorem ipsum dolor
          RAW

          let!(:article) { create(:ticket_article, ticket: ticket, message_id: '<20150830145601.30.608882@edenhofer.zammad.com>') }
        end

        shared_examples 'adds message to ticket' do
          it 'adds message to ticket' do
            expect { described_class.new.process({}, raw_mail) }
              .to change { ticket.articles.reload.length }.by(1)
          end
        end

        shared_examples 'creates a new ticket' do
          it 'creates a new ticket' do
            expect { described_class.new.process({}, raw_mail) }
              .to change(Ticket, :count).by(1)
              .and not_change { ticket.articles.reload.length }
          end
        end

        context 'when configured to search subject_references' do

          context 'when subject contains ticket reference' do
            include_context 'ticket reference in subject'
            include_examples 'adds message to ticket'

            context 'alongside other, invalid ticket references' do
              let(:raw_mail) { <<~RAW.chomp }
                From: me@example.com
                To: customer@example.com
                Subject: [#{Setting.get('ticket_hook') + Setting.get('ticket_hook_divider') + Ticket::Number.generate}] #{ticket_ref}

                Lorem ipsum dolor
              RAW

              include_examples 'adds message to ticket'
            end

            context 'and ticket is closed' do
              before { ticket.update(state: Ticket::State.find_by(name: 'closed')) }

              include_examples 'adds message to ticket'
            end

            context 'but ticket group’s #follow_up_possible attribute is "new_ticket"' do
              before { ticket.group.update(follow_up_possible: 'new_ticket') }

              context 'and ticket is open' do
                include_examples 'adds message to ticket'
              end

              context 'and ticket is closed' do
                before { ticket.update(state: Ticket::State.find_by(name: 'closed')) }

                include_examples 'creates a new ticket'
              end

              context 'and ticket is merged' do
                before { ticket.update(state: Ticket::State.find_by(name: 'merged')) }

                include_examples 'creates a new ticket'
              end
            end

            context 'and "ticket_hook" setting is non-default value' do
              before { Setting.set('ticket_hook', 'VD-Ticket#') }

              include_examples 'adds message to ticket'
            end

            # https://github.com/zammad/zammad/issues/5170
            context 'when email is encrypted, including subject' do
              let!(:ticket)  { create(:ticket, number: 31_337) }
              let(:raw_mail) { Rails.root.join('spec/fixtures/files/pgp/mail/mail-combined.box').read.to_s }

              before do
                Setting.set('ticket_number_ignore_system_id', true) # this is needed to allow hardcoded ticket reference
                Setting.set('pgp_integration', true)

                (1..3).each { |i| create(:pgp_key, :with_private, fixture: "pgp#{i}@example.com") }
              end

              include_examples 'adds message to ticket'
            end
          end

          context 'when body contains ticket reference' do
            include_context 'ticket reference in body'
            include_examples 'creates a new ticket'
          end

          context 'when text/plain attachment contains ticket reference' do
            include_context 'ticket reference in text/plain attachment'
            include_examples 'creates a new ticket'
          end

          context 'when text/html attachment (as content) contains ticket reference' do
            include_context 'ticket reference in text/html (as content) attachment'
            include_examples 'creates a new ticket'
          end

          context 'when text/html attachment (attribute) contains ticket reference' do
            include_context 'ticket reference in text/html (attribute) attachment'
            include_examples 'creates a new ticket'
          end

          context 'when image/jpg attachment contains ticket reference' do
            include_context 'ticket reference in image/jpg attachment'
            include_examples 'creates a new ticket'
          end

          context 'when In-Reply-To header contains article message-id' do
            include_context 'ticket reference in In-Reply-To header'
            include_examples 'creates a new ticket'

            context 'and subject matches article subject' do
              let(:raw_mail) { <<~RAW.chomp }
                From: customer@example.com
                To: me@example.com
                Subject: AW: RE: #{article.subject}
                In-Reply-To: #{article.message_id}

                Lorem ipsum dolor
              RAW

              include_examples 'adds message to ticket'
            end

            context 'and "ticket_hook_position" setting is "none"' do
              before { Setting.set('ticket_hook_position', 'none') }

              let(:raw_mail) { <<~RAW.chomp }
                From: customer@example.com
                To: me@example.com
                Subject: RE: Foo bar
                In-Reply-To: #{article.message_id}

                Lorem ipsum dolor
              RAW

              include_examples 'adds message to ticket'
            end
          end

          context 'when References header contains article message-id' do
            include_context 'ticket reference in References header'
            include_examples 'creates a new ticket'

            context 'and Auto-Submitted header reads "auto-replied"' do
              let(:raw_mail) { <<~RAW.chomp }
                From: me@example.com
                To: customer@example.com
                Subject: no reference
                References: #{article.message_id}
                Auto-Submitted: auto-replied

                Lorem ipsum dolor
              RAW

              include_examples 'adds message to ticket'
            end

            context 'and subject matches article subject' do
              let(:raw_mail) { <<~RAW.chomp }
                From: customer@example.com
                To: me@example.com
                Subject: AW: RE: #{article.subject}
                References: #{article.message_id}

                Lorem ipsum dolor
              RAW

              include_examples 'adds message to ticket'
            end

            context 'and "ticket_hook_position" setting is "none"' do
              before { Setting.set('ticket_hook_position', 'none') }

              let(:raw_mail) { <<~RAW.chomp }
                From: customer@example.com
                To: me@example.com
                Subject: RE: Foo bar
                References: #{article.message_id}

                Lorem ipsum dolor
              RAW

              include_examples 'adds message to ticket'
            end
          end
        end

        context 'when configured to search body' do
          before { Setting.set('postmaster_follow_up_search_in', 'body') }

          context 'when subject contains ticket reference' do
            include_context 'ticket reference in subject'
            include_examples 'adds message to ticket'
          end

          context 'when body contains ticket reference' do
            context 'in visible text' do
              include_context 'ticket reference in body'
              include_examples 'adds message to ticket'
            end

            context 'in visible text with a linebreak' do
              let(:raw_mail) { <<~RAW.chomp }
                From: me@example.com
                To: customer@example.com
                Subject: no reference

                Lorem ipsum dolor #{ticket_ref}
                consetetur sadipscing elitr
                sed diam nonumy eirmod
              RAW

              include_examples 'adds message to ticket'
            end

            context 'as part of a larger word' do
              let(:ticket_ref) { "Foo#{Setting.get('ticket_hook')}#{Setting.get('ticket_hook_divider')}#{ticket.number}bar" }

              include_context 'ticket reference in body'
              include_examples 'creates a new ticket'
            end

            context 'between html tags' do
              include_context 'ticket reference in body (text/html)'
              include_examples 'adds message to ticket'
            end

            context 'in html attributes' do
              let(:ticket_ref) { %(<table bgcolor="#{Setting.get('ticket_hook')}#{Setting.get('ticket_hook_divider')}#{ticket.number}"> </table>) }

              include_context 'ticket reference in body (text/html)'
              include_examples 'creates a new ticket'
            end
          end

          context 'when text/plain attachment contains ticket reference' do
            include_context 'ticket reference in text/plain attachment'
            include_examples 'creates a new ticket'
          end

          context 'when text/html attachment (as content) contains ticket reference' do
            include_context 'ticket reference in text/html (as content) attachment'
            include_examples 'creates a new ticket'
          end

          context 'when text/html attachment (attribute) contains ticket reference' do
            include_context 'ticket reference in text/html (attribute) attachment'
            include_examples 'creates a new ticket'
          end

          context 'when image/jpg attachment contains ticket reference' do
            include_context 'ticket reference in image/jpg attachment'
            include_examples 'creates a new ticket'
          end

          context 'when In-Reply-To header contains article message-id' do
            include_context 'ticket reference in In-Reply-To header'
            include_examples 'creates a new ticket'

            context 'and Auto-Submitted header reads "auto-replied"' do
              let(:raw_mail) { <<~RAW.chomp }
                From: me@example.com
                To: customer@example.com
                Subject: no reference
                References: #{article.message_id}
                Auto-Submitted: auto-replied

                Lorem ipsum dolor
              RAW

              include_examples 'adds message to ticket'
            end
          end

          context 'when References header contains article message-id' do
            include_context 'ticket reference in References header'
            include_examples 'creates a new ticket'
          end
        end

        context 'when configured to search attachments' do
          before { Setting.set('postmaster_follow_up_search_in', 'attachment') }

          context 'when subject contains ticket reference' do
            include_context 'ticket reference in subject'
            include_examples 'adds message to ticket'
          end

          context 'when body contains ticket reference' do
            include_context 'ticket reference in body'
            include_examples 'creates a new ticket'
          end

          context 'when text/plain attachment contains ticket reference' do
            include_context 'ticket reference in text/plain attachment'
            include_examples 'adds message to ticket'
          end

          context 'when text/html attachment (as content) contains ticket reference' do
            include_context 'ticket reference in text/html (as content) attachment'
            include_examples 'adds message to ticket'
          end

          context 'when text/html attachment (attribute) contains ticket reference' do
            include_context 'ticket reference in text/html (attribute) attachment'
            include_examples 'creates a new ticket'
          end

          context 'when image/jpg attachment contains ticket reference' do
            include_context 'ticket reference in image/jpg attachment'
            include_examples 'creates a new ticket'
          end

          context 'when In-Reply-To header contains article message-id' do
            include_context 'ticket reference in In-Reply-To header'
            include_examples 'creates a new ticket'
          end

          context 'when References header contains article message-id' do
            include_context 'ticket reference in References header'
            include_examples 'creates a new ticket'

            context 'and Auto-Submitted header reads "auto-replied"' do
              let(:raw_mail) { <<~RAW.chomp }
                From: me@example.com
                To: customer@example.com
                Subject: no reference
                References: #{article.message_id}
                Auto-Submitted: auto-replied

                Lorem ipsum dolor
              RAW

              include_examples 'adds message to ticket'
            end
          end

          # https://github.com/zammad/zammad/issues/6141
          context 'when attachment is malformatted and ticket hook is UTF8' do
            let(:raw_mail) { <<~RAW.chomp }
              From: sender@example.org
              To: support@example.com
              Subject: test
              Content-Type: multipart/mixed; boundary="===============2843907148225004358=="

              --===============2843907148225004358==
              Content-Type: =?utf-8?b?YXBwbGljYXRpb24vcGRmOyBuYW1lPSJzYW1wbMSZLnBkZiI=?=
              MIME-Version: 1.0
              Content-Transfer-Encoding: base64
              Content-Disposition: attachment;
               filename="=?utf-8?b?c2FtcGzEmS5wZGY=?="

              JVBERi0xLjQKJZOMi54gUmVwb3J0TGFiIEdlbmVyYXRlZCBQREYgZG9jdW1lbnQgKG9wZW5zb3VyY2UpCjEgMCBvYmoKPDwKL0YxIDIgMCBSCj4+CmVuZG9iagoyIDAgb2JqCjw8Ci9CYXNlRm9udCAvSGVsdmV0aWNhIC9FbmNvZGluZyAvV2luQW5zaUVuY29kaW5nIC9OYW1lIC9GMSAvU3VidHlwZSAvVHlwZTEgL1R5cGUgL0ZvbnQKPj4KZW5kb2JqCjMgMCBvYmoKPDwKL0NvbnRlbnRzIDcgMCBSIC9NZWRpYUJveCBbIDAgMCA1OTUuMjc1NiA4NDEuODg5OCBdIC9QYXJlbnQgNiAwIFIgL1Jlc291cmNlcyA8PAovRm9udCAxIDAgUiAvUHJvY1NldCBbIC9QREYgL1RleHQgL0ltYWdlQiAvSW1hZ2VDIC9JbWFnZUkgXQo+PiAvUm90YXRlIDAgL1RyYW5zIDw8Cgo+PiAKICAvVHlwZSAvUGFnZQo+PgplbmRvYmoKNCAwIG9iago8PAovUGFnZU1vZGUgL1VzZU5vbmUgL1BhZ2VzIDYgMCBSIC9UeXBlIC9DYXRhbG9nCj4+CmVuZG9iago1IDAgb2JqCjw8Ci9BdXRob3IgKFwoYW5vbnltb3VzXCkpIC9DcmVhdGlvbkRhdGUgKEQ6MjAyNjA1MTgxODI0MjcrMDMnMDAnKSAvQ3JlYXRvciAoXCh1bnNwZWNpZmllZFwpKSAvS2V5d29yZHMgKCkgL01vZERhdGUgKEQ6MjAyNjA1MTgxODI0MjcrMDMnMDAnKSAvUHJvZHVjZXIgKFJlcG9ydExhYiBQREYgTGlicmFyeSAtIFwob3BlbnNvdXJjZVwpKSAKICAvU3ViamVjdCAoXCh1bnNwZWNpZmllZFwpKSAvVGl0bGUgKFwoYW5vbnltb3VzXCkpIC9UcmFwcGVkIC9GYWxzZQo+PgplbmRvYmoKNiAwIG9iago8PAovQ291bnQgMSAvS2lkcyBbIDMgMCBSIF0gL1R5cGUgL1BhZ2VzCj4+CmVuZG9iago3IDAgb2JqCjw8Ci9GaWx0ZXIgWyAvQVNDSUk4NURlY29kZSAvRmxhdGVEZWNvZGUgXSAvTGVuZ3RoIDE0NAo+PgpzdHJlYW0KR2FwcFZdYWQ6bSY7OXEtTUNEREEvJlotKjsoLCEvJUslTW0rdUVXYDNbMGJdMUdkbyJbInQ0XyljLzVfUlFyVFAic21bWkRHZFoiJ1JlNk0rQTQuPy05JjVsNWVHclpQXGZVKSQiLypXZzdkTDJqPkUuLzQwSk9oLEooMlNfKC5LaSVYSmA6JTdwMTZnQX4+ZW5kc3RyZWFtCmVuZG9iagp4cmVmCjAgOAowMDAwMDAwMDAwIDY1NTM1IGYgCjAwMDAwMDAwNjEgMDAwMDAgbiAKMDAwMDAwMDA5MiAwMDAwMCBuIAowMDAwMDAwMTk5IDAwMDAwIG4gCjAwMDAwMDA0MDIgMDAwMDAgbiAKMDAwMDAwMDQ3MCAwMDAwMCBuIAowMDAwMDAwNzUwIDAwMDAwIG4gCjAwMDAwMDA4MDkgMDAwMDAgbiAKdHJhaWxlcgo8PAovSUQgCls8NTFhNWRhZmFkNmRkOGZmYTYwZGExZTI2NjMwYzUyOTQ+PDUxYTVkYWZhZDZkZDhmZmE2MGRhMWUyNjYzMGM1Mjk0Pl0KJSBSZXBvcnRMYWIgZ2VuZXJhdGVkIFBERiBkb2N1bWVudCAtLSBkaWdlc3QgKG9wZW5zb3VyY2UpCgovSW5mbyA1IDAgUgovUm9vdCA0IDAgUgovU2l6ZSA4Cj4+CnN0YXJ0eHJlZgoxMDQzCiUlRU9GCg==

              --===============2843907148225004358==--
            RAW

            before do
              Setting.set('ticket_hook', 'samplę')
            end

            include_examples 'creates a new ticket'
          end
        end

        context 'when configured to search headers' do
          before { Setting.set('postmaster_follow_up_search_in', 'references') }

          context 'when subject contains ticket reference' do
            include_context 'ticket reference in subject'
            include_examples 'adds message to ticket'
          end

          context 'when body contains ticket reference' do
            include_context 'ticket reference in body'
            include_examples 'creates a new ticket'
          end

          context 'when text/plain attachment contains ticket reference' do
            include_context 'ticket reference in text/plain attachment'
            include_examples 'creates a new ticket'
          end

          context 'when text/html attachment (as content) contains ticket reference' do
            include_context 'ticket reference in text/html (as content) attachment'
            include_examples 'creates a new ticket'
          end

          context 'when text/html attachment (attribute) contains ticket reference' do
            include_context 'ticket reference in text/html (attribute) attachment'
            include_examples 'creates a new ticket'
          end

          context 'when image/jpg attachment contains ticket reference' do
            include_context 'ticket reference in image/jpg attachment'
            include_examples 'creates a new ticket'
          end

          context 'when In-Reply-To header contains article message-id' do
            include_context 'ticket reference in In-Reply-To header'
            include_examples 'adds message to ticket'
          end

          context 'when References header contains article message-id' do
            include_context 'ticket reference in References header'
            include_examples 'adds message to ticket'

            context 'that matches two separate tickets' do
              let!(:newer_ticket)  { create(:ticket) }
              let!(:newer_article) { create(:ticket_article, ticket: newer_ticket, message_id: article.message_id) }

              it 'returns more recently created ticket' do
                expect(described_class.new.process({}, raw_mail).first).to eq(newer_ticket)
              end

              it 'adds message to more recently created ticket' do
                expect { described_class.new.process({}, raw_mail) }
                  .to change { newer_ticket.articles.reload.count }.by(1)
                  .and not_change { ticket.articles.reload.count }
              end
            end

            context 'and Auto-Submitted header reads "auto-replied"' do
              let(:raw_mail) { <<~RAW.chomp }
                From: me@example.com
                To: customer@example.com
                Subject: no reference
                References: #{article.message_id}
                Auto-Submitted: auto-replied

                Lorem ipsum dolor
              RAW

              include_examples 'adds message to ticket'
            end
          end
        end

        context 'when configured to search everything' do
          before { Setting.set('postmaster_follow_up_search_in', %w[body attachment references]) }

          context 'when subject contains ticket reference' do
            include_context 'ticket reference in subject'
            include_examples 'adds message to ticket'
          end

          context 'when body contains ticket reference' do
            include_context 'ticket reference in body'
            include_examples 'adds message to ticket'
          end

          context 'when text/plain attachment contains ticket reference' do
            include_context 'ticket reference in text/plain attachment'
            include_examples 'adds message to ticket'
          end

          context 'when text/html attachment (as content) contains ticket reference' do
            include_context 'ticket reference in text/html (as content) attachment'
            include_examples 'adds message to ticket'
          end

          context 'when text/html attachment (attribute) contains ticket reference' do
            include_context 'ticket reference in text/html (attribute) attachment'
            include_examples 'creates a new ticket'
          end

          context 'when image/jpg attachment contains ticket reference' do
            include_context 'ticket reference in image/jpg attachment'
            include_examples 'creates a new ticket'
          end

          context 'when In-Reply-To header contains article message-id' do
            include_context 'ticket reference in In-Reply-To header'
            include_examples 'adds message to ticket'
          end

          context 'when References header contains article message-id' do
            include_context 'ticket reference in References header'
            include_examples 'adds message to ticket'

            context 'and Auto-Submitted header reads "auto-replied"' do
              let(:raw_mail) { <<~RAW.chomp }
                From: me@example.com
                To: customer@example.com
                Subject: no reference
                References: #{article.message_id}
                Auto-Submitted: auto-replied

                Lorem ipsum dolor
              RAW

              include_examples 'adds message to ticket'
            end
          end
        end
      end

      context 'for a closed ticket' do
        let(:ticket) { create(:ticket, state_name: 'closed') }

        let(:raw_mail) { <<~RAW.chomp }
          From: me@example.com
          To: customer@example.com
          Subject: #{ticket_ref}

          Lorem ipsum dolor
        RAW

        it 'reopens it' do
          expect { described_class.new.process({}, raw_mail) }
            .to change { ticket.reload.state.name }.to('open')
        end

        context 'when group has follow_up_assignment true' do
          let(:group) { create(:group, follow_up_assignment: true) }
          let(:agent)  { create(:agent, groups: [group]) }
          let(:ticket) { create(:ticket, state_name: 'closed', owner: agent, group: group) }

          it 'does not change the owner' do
            expect { described_class.new.process({}, raw_mail) }
              .not_to change { ticket.reload.owner.login }
          end
        end

        context 'when group has follow_up_assignment false' do
          let(:group) { create(:group, follow_up_assignment: false) }
          let(:agent)  { create(:agent, groups: [group]) }
          let(:ticket) { create(:ticket, state_name: 'closed', owner: agent, group: group) }

          it 'does change the owner' do
            expect { described_class.new.process({}, raw_mail) }
              .to change { ticket.reload.owner.login }.to eq(User.find(1).login)
          end
        end
      end
    end

    describe 'assigning ticket.customer' do
      let(:agent) { create(:agent) }
      let(:customer) { create(:customer) }

      let(:raw_mail) { <<~RAW.chomp }
        From: #{agent.email}
        To: #{customer.email}
        Subject: Foo

        Lorem ipsum dolor
      RAW

      context 'when "postmaster_sender_is_agent_search_for_customer" setting is true (default)' do
        it 'sets ticket.customer to user with To: email' do
          expect { described_class.new.process({}, raw_mail) }
            .to change(Ticket, :count).by(1)

          expect(Ticket.last.customer).to eq(customer)
        end
      end

      context 'when "postmaster_sender_is_agent_search_for_customer" setting is false' do
        before { Setting.set('postmaster_sender_is_agent_search_for_customer', false) }

        it 'sets ticket.customer to user with To: email' do
          expect { described_class.new.process({}, raw_mail) }
            .to change(Ticket, :count).by(1)

          expect(Ticket.last.customer).to eq(agent)
        end
      end
    end

    describe 'formatting to/from addresses' do
      # see https://github.com/zammad/zammad/issues/2198
      context 'when sender address contains spaces (#2198)' do
        let(:mail_file)    { Rails.root.join('test/data/mail/mail071.box') }
        let(:sender_email) { 'powerquadrantsystem@example.com' }

        it 'removes them before creating a new user' do
          expect { described_class.new.process({}, raw_mail) }
            .to change { User.exists?(email: sender_email) }
        end

        it 'marks new user email as invalid' do
          described_class.new.process({}, raw_mail)

          expect(User.find_by(email: sender_email).preferences)
            .to include('mail_delivery_failed' => true)
            .and include('mail_delivery_failed_reason' => 'invalid email')
            .and include('mail_delivery_failed_data' => a_kind_of(ActiveSupport::TimeWithZone))
        end
      end

      # see https://github.com/zammad/zammad/issues/2254
      context 'when sender address contains > (#2254)' do
        let(:mail_file) { Rails.root.join('test/data/mail/mail076.box') }
        let(:sender_email) { 'millionslotteryspaintransfer@example.com' }

        it 'removes them before creating a new user' do
          expect { described_class.new.process({}, raw_mail) }
            .to change { User.exists?(email: sender_email) }
        end

        it 'marks new user email as invalid' do
          described_class.new.process({}, raw_mail)

          expect(User.find_by(email: sender_email).preferences)
            .to include('mail_delivery_failed' => true)
            .and include('mail_delivery_failed_reason' => 'invalid email')
            .and include('mail_delivery_failed_data' => a_kind_of(ActiveSupport::TimeWithZone))
        end
      end
    end

    describe 'handling senders that are no valid email address' do
      shared_examples 'creating a ticket without a failed email' do
        it 'creates a ticket and no failed email' do
          expect { described_class.new.process({}, raw_mail) }
            .to change(Ticket, :count).by(1)
            .and not_change(FailedEmail, :count)
        end
      end

      context 'when the sender address is invalid' do
        let(:mail_file) { Rails.root.join('test/data/mail/mail121.box') }

        include_examples 'creating a ticket without a failed email'

        it 'creates a customer with the address as login and no email' do
          ticket, = described_class.new.process({}, raw_mail)

          expect(ticket.customer).to have_attributes(
            login:     'foo@bar@example.com',
            email:     '',
            firstname: 'Foo',
            lastname:  'Bar',
          )
        end

        it 'keeps the body readable' do
          _ticket, article, = described_class.new.process({}, raw_mail)

          expect(article.body).to include('could you please tell me the status of my order?')
        end

        it 'assigns a second mail from the same sender to the same customer' do
          first_ticket, = described_class.new.process({}, raw_mail)

          expect { described_class.new.process({}, raw_mail.sub('invalid-from-20261026091244', 'invalid-from-second')) }
            .to not_change(User, :count)

          expect(Ticket.last.customer).to eq(first_ticket.customer)
        end
      end

      context 'when the invalid sender address is padded with spaces' do
        let(:raw_mail) { <<~RAW.chomp }
          From: Foo < foo@bar@example.com >
          To: support@example.com
          Subject: Foo

          Lorem ipsum dolor
        RAW

        include_examples 'creating a ticket without a failed email'

        it 'assigns a second mail from the same sender to the same customer' do
          first_ticket, = described_class.new.process({}, raw_mail)
          second_ticket, = described_class.new.process({}, raw_mail.sub('Subject: Foo', 'Subject: Bar'))

          expect(second_ticket.customer).to eq(first_ticket.customer)
        end

        it 'does not mark the customer with a failed delivery, since no address is kept' do
          ticket, = described_class.new.process({}, raw_mail)

          expect(ticket.customer.preferences).not_to include('mail_delivery_failed')
        end
      end

      context 'when the sender is a word that is no address' do
        let(:raw_mail) { <<~RAW.chomp }
          From: domain\\jdoe
          To: support@example.com
          Subject: Foo

          Lorem ipsum dolor
        RAW

        include_examples 'creating a ticket without a failed email'

        it 'creates a customer with the word as login and no email' do
          ticket, = described_class.new.process({}, raw_mail)

          expect(ticket.customer).to have_attributes(login: 'domain\\jdoe', email: '')
        end
      end

      context 'when the mail has no sender field' do
        let(:mail_file) { Rails.root.join('test/data/mail/no_sender.box') }

        include_examples 'creating a ticket without a failed email'

        it 'assigns the system account as customer' do
          ticket, article, = described_class.new.process({}, raw_mail)

          expect(ticket.customer_id).to eq(1)
          expect(article).to have_attributes(created_by_id: 1, sender: Ticket::Article::Sender.lookup(name: 'Customer'))
        end

        it 'creates no user for the sender' do
          expect { described_class.new.process({}, raw_mail) }
            .to not_change { User.where.not(email: 'support@example.com').count }
        end
      end

      context 'when the sender is an empty group' do
        let(:raw_mail) { <<~RAW.chomp }
          From: undisclosed-recipients:;
          To: support@example.com
          Subject: Foo

          Lorem ipsum dolor
        RAW

        include_examples 'creating a ticket without a failed email'

        it 'assigns the system account as customer' do
          ticket, = described_class.new.process({}, raw_mail)

          expect(ticket.customer_id).to eq(1)
        end
      end
    end

    describe 'signature detection', performs_jobs: true do
      let(:raw_mail) { header + File.read(message_file) }

      let(:header) { <<~HEADER }
        From: Bob.Smith@music.com
        To: test@zammad.org
        Subject: test

      HEADER

      context 'for emails from an unrecognized email address' do
        let(:message_file) { Rails.root.join('test/data/email_signature_detection/client_a_1.txt') }

        it 'does not detect signatures' do
          described_class.new.process({}, raw_mail)

          expect { perform_enqueued_jobs }
            .to not_change { Ticket.last.customer.preferences[:signature_detection] }.from(nil)
            .and not_change { Ticket.last.articles.reload.first.preferences[:signature_detection] }.from(nil)
        end
      end

      context 'for emails from a previously processed sender' do
        before do
          described_class.new.process({}, header + File.read(previous_message_file))
        end

        let(:previous_message_file) { Rails.root.join('test/data/email_signature_detection/client_a_1.txt') }

        let(:message_file) { Rails.root.join('test/data/email_signature_detection/client_a_2.txt') }

        it 'sets detected signature on user (in a background job)' do
          described_class.new.process({}, raw_mail)

          expect { perform_enqueued_jobs }
            .to change { Ticket.last.customer.preferences[:signature_detection] }
        end

        it 'sets line of detected signature on article (in a background job)' do
          described_class.new.process({}, raw_mail)

          expect { perform_enqueued_jobs }
            .to change { Ticket.last.articles.reload.first.preferences[:signature_detection] }.to(20)
        end
      end
    end

    describe 'charset handling' do
      # see https://github.com/zammad/zammad/issues/2224
      context 'when header specifies Windows-1258 charset (#2224)' do
        let(:mail_file) { Rails.root.join('test/data/mail/mail072.box') }

        it 'does not raise Encoding::ConverterNotFoundError' do
          expect { described_class.new.process({}, raw_mail) }
            .not_to raise_error
        end
      end

      context 'when attachment for follow up check contains invalid charsets (#2808)' do
        let(:mail_file) { Rails.root.join('test/data/mail/mail085.box') }

        before { Setting.set('postmaster_follow_up_search_in', %w[attachment body]) }

        it 'does not raise Encoding::CompatibilityError:' do
          expect { described_class.new.process({}, raw_mail) }
            .not_to raise_error
        end
      end

    end

    describe 'attachment handling' do
      context 'with header "Content-Transfer-Encoding: x-uuencode"' do
        let(:mail_file) { Rails.root.join('test/data/mail/mail078-content_transfer_encoding_x_uuencode.box') }
        let(:article)   { described_class.new.process({}, raw_mail).second }

        it 'does not raise RuntimeError' do
          expect { described_class.new.process({}, raw_mail) }
            .not_to raise_error
        end

        it 'parses the content correctly' do
          expect(article.attachments.first.filename).to eq('PGP_Cmts_on_12-14-01_Pkg.txt')
          expect(article.attachments.first.content).to eq('Hello Zammad')
        end
      end

      # https://github.com/zammad/zammad/issues/3529
      context 'Attachments sent by Zammad not shown in Outlook' do
        subject(:mail) do
          Channel::EmailBuild.build(
            from:         'sender@example.com',
            to:           'recipient@example.com',
            body:         body,
            content_type: 'text/html',
            attachments:  Store.where(filename: 'super-seven.jpg')
          )
        end

        let(:mail_file) { Rails.root.join('test/data/mail/mail101.box') }

        before do
          described_class.new.process({}, raw_mail)
        end

        context 'when no reference in body' do
          let(:body) { 'no reference here' }

          it 'does not have content disposition inline' do
            expect(mail.to_s).to include('Content-Disposition: attachment').and not_include('Content-Disposition: inline')
          end
        end

        context 'when reference in body' do
          let(:body) { %(somebody with some text <img src="cid:#{Store.find_by(filename: 'super-seven.jpg').preferences['Content-ID']}">) }

          it 'does have content disposition inline' do
            expect(mail.to_s).to include('Content-Disposition: inline').and not_include('Content-Disposition: attachment')
          end

          context 'when encoded as ISO-8859-1' do
            let(:body) { super().encode('ISO-8859-1') }

            it 'does not raise exception' do
              expect { mail.to_s }.not_to raise_error
            end
          end
        end
      end
    end

    describe 'inline image handling' do
      # see https://github.com/zammad/zammad/issues/2486
      context 'when image is large but not resizable' do
        let(:mail_file) { Rails.root.join('test/data/mail/mail079.box') }
        let(:attachment) { article.attachments.to_a.find { |i| i.filename == 'a.jpg' } }
        let(:article)    { described_class.new.process({}, raw_mail).second }

        it "doesn't set resizable preference" do
          expect(attachment.filename).to eq('a.jpg')
          expect(attachment.preferences).not_to include('resizable' => true)
        end
      end
    end

    describe 'ServiceNow handling' do

      context 'new Ticket' do
        let(:mail_file) { Rails.root.join('test/data/mail/mail089.box') }

        it 'creates an ExternalSync reference' do
          described_class.new.process({}, raw_mail)

          expect(ExternalSync.last).to have_attributes(
            source:    'ServiceNow-example@service-now.com',
            source_id: 'INC678439',
            object:    'Ticket',
            o_id:      Ticket.last.id,
          )
        end

        context 'when the incident number is followed by a colon' do
          let(:raw_mail) { super().sub('INC678439 --', 'INC678439: --') }

          it 'creates an ExternalSync reference' do
            described_class.new.process({}, raw_mail)

            expect(ExternalSync.last).to have_attributes(
              source:    'ServiceNow-example@service-now.com',
              source_id: 'INC678439',
              object:    'Ticket',
              o_id:      Ticket.last.id,
            )
          end
        end
      end

      context 'follow up' do

        let(:mail_file) { Rails.root.join('test/data/mail/mail090.box') }
        let(:ticket)    { create(:ticket) }
        let!(:external_sync) do
          create(:external_sync,
                 source:    'ServiceNow-example@service-now.com',
                 source_id: 'INC678439',
                 object:    'Ticket',
                 o_id:      ticket.id,)
        end

        it 'adds Article to existing Ticket' do
          expect { described_class.new.process({}, raw_mail) }.to change { ticket.reload.articles.reload.count }
        end

        context 'key insensitive sender address' do

          let(:raw_mail) { super().gsub('example@service-now.com', 'Example@Service-Now.com') }

          it 'adds Article to existing Ticket' do
            expect { described_class.new.process({}, raw_mail) }.to change { ticket.reload.articles.reload.count }
          end
        end

        context 'when the incident number is followed by a colon' do
          let(:raw_mail) { super().sub('Incident_INC678439_--', 'Incident_INC678439:_--') }

          it 'adds Article to existing Ticket' do
            expect { described_class.new.process({}, raw_mail) }.to change { ticket.reload.articles.reload.count }
          end
        end
      end
    end

    describe 'Jira handling' do

      context 'new Ticket' do
        let(:mail_file) { Rails.root.join('test/data/mail/mail103.box') }

        it 'creates an ExternalSync reference' do
          described_class.new.process({}, raw_mail)

          expect(ExternalSync.last).to have_attributes(
            source:    'Jira-example@jira.com',
            source_id: 'SYS-422',
            object:    'Ticket',
            o_id:      Ticket.last.id,
          )
        end
      end

      context 'follow up' do

        let(:mail_file) { Rails.root.join('test/data/mail/mail104.box') }
        let(:ticket)    { create(:ticket) }
        let!(:external_sync) do
          create(:external_sync,
                 source:    'Jira-example@jira.com',
                 source_id: 'SYS-422',
                 object:    'Ticket',
                 o_id:      ticket.id,)
        end

        it 'adds Article to existing Ticket' do
          expect { described_class.new.process({}, raw_mail) }.to change { ticket.reload.articles.reload.count }
        end

        context 'key insensitive sender address' do

          let(:raw_mail) { super().gsub('example@service-now.com', 'Example@Service-Now.com') }

          it 'adds Article to existing Ticket' do
            expect { described_class.new.process({}, raw_mail) }.to change { ticket.reload.articles.reload.count }
          end
        end
      end
    end

    describe 'XSS protection' do

      before do
        # XSS processing may run into a timeout on slow CI systems, so turn the timeout off for the test.
        stub_const("#{HtmlSanitizer}::PROCESSING_TIMEOUT", nil)
      end

      let(:article) { described_class.new.process({}, raw_mail).second }

      let(:raw_mail) { <<~RAW.chomp }
        From: ME Bob <me@example.com>
        To: customer@example.com
        Subject: some subject
        Content-Type: #{content_type}
        MIME-Version: 1.0

        no HTML <script type="text/javascript">alert('XSS')</script>
      RAW

      context 'for Content-Type: text/html' do
        let(:content_type) { 'text/html' }

        it 'removes injected <script> tags from body' do
          expect(article.body).to eq('no HTML')
        end
      end

      context 'for Content-Type: text/plain' do
        let(:content_type) { 'text/plain' }

        it 'leaves body as-is' do
          expect(article.body).to eq(<<~SANITIZED.chomp)
            no HTML <script type="text/javascript">alert('XSS')</script>
          SANITIZED
        end
      end
    end

    context 'for “delivery failed” notifications (a.k.a. bounce messages)' do
      let(:ticket)     { article.ticket }
      let(:article)    { create(:ticket_article, sender_name: 'Agent', message_id: message_id) }
      let(:message_id) { raw_mail[%r{(?<=^(References|Message-ID): )\S*}] }

      context 'with future retries (delayed)' do
        let(:mail_file) { Rails.root.join('test/data/mail/mail078.box') }

        context 'on a closed ticket' do
          before { ticket.update(state: Ticket::State.find_by(name: 'closed')) }

          it 'sets #preferences on resulting ticket to { "send-auto-responses" => false, "is-auto-reponse" => true }' do
            article = described_class.new.process({}, raw_mail).second
            expect(article.preferences)
              .to include('send-auto-response' => false, 'is-auto-response' => true)
          end

          it 'returns a Mail object with an x-zammad-out-of-office header' do
            output_mail = described_class.new.process({}, raw_mail).last
            expect(output_mail).to include('x-zammad-out-of-office': true)
          end

          it 'finds the article referenced in the bounce message headers, then adds the bounce message to its ticket' do
            expect { described_class.new.process({}, raw_mail) }
              .to change { ticket.articles.reload.count }.by(1)
          end

          it 'does not re-open the ticket' do
            expect { described_class.new.process({}, raw_mail) }
              .not_to change { ticket.reload.state.name }.from('closed')
          end
        end
      end

      context 'with no future retries (undeliverable): sample input 1' do
        let(:mail_file) { Rails.root.join('test/data/mail/mail033-undelivered-mail-returned-to-sender.box') }

        context 'for original message sent by Agent' do
          it 'sets #preferences on resulting ticket to { "send-auto-responses" => false, "is-auto-reponse" => true }' do
            article = described_class.new.process({}, raw_mail).second
            expect(article.preferences)
              .to include('send-auto-response' => false, 'is-auto-response' => true)
          end

          it 'finds the article referenced in the bounce message headers, then adds the bounce message to its ticket' do
            expect { described_class.new.process({}, raw_mail) }
              .to change { ticket.articles.reload.count }.by(1)
          end

          it 'does not alter the ticket state' do
            expect { described_class.new.process({}, raw_mail) }
              .not_to change { ticket.reload.state.name }.from('open')
          end
        end

        context 'for original message sent by Customer' do
          let(:article) { create(:ticket_article, sender_name: 'Customer', message_id: message_id) }

          it 'sets #preferences on resulting ticket to { "send-auto-responses" => false, "is-auto-reponse" => true }' do
            article = described_class.new.process({}, raw_mail).second
            expect(article.preferences)
              .to include('send-auto-response' => false, 'is-auto-response' => true)
          end

          it 'finds the article referenced in the bounce message headers, then adds the bounce message to its ticket' do
            expect { described_class.new.process({}, raw_mail) }
              .to change { ticket.articles.reload.count }.by(1)
          end

          it 'does not alter the ticket state' do
            expect { described_class.new.process({}, raw_mail) }
              .not_to change { ticket.reload.state.name }.from('new')
          end
        end
      end

      context 'with no future retries (undeliverable): sample input 2' do
        let(:mail_file) { Rails.root.join('test/data/mail/mail055.box') }

        it 'finds the article referenced in the bounce message headers, then adds the bounce message to its ticket' do
          expect { described_class.new.process({}, raw_mail) }
            .to change { ticket.articles.reload.count }.by(1)
        end

        it 'does not alter the ticket state' do
          expect { described_class.new.process({}, raw_mail) }
            .not_to change { ticket.reload.state.name }.from('open')
        end
      end
    end

    context 'for “out-of-office” notifications (a.k.a. auto-response messages)' do
      let(:raw_mail) { <<~RAW.chomp }
        From: me@example.com
        To: customer@example.com
        Subject: #{subject_line}

        Some Text
      RAW
      let(:subject_line) { 'Lorem ipsum dolor' }

      it 'applies the OutOfOfficeCheck filter to given message' do
        expect(Channel::Filter::OutOfOfficeCheck)
          .to receive(:run)
          .with(kind_of(Hash), hash_including(subject: subject_line), kind_of(Hash))

        described_class.new.process({}, raw_mail)
      end

      context 'on an existing, closed ticket' do
        let(:ticket) { create(:ticket, state_name: 'closed') }
        let(:subject_line) { ticket.subject_build('Lorem ipsum dolor') }

        context 'when OutOfOfficeCheck filter applies x-zammad-out-of-office: false' do
          before do
            allow(Channel::Filter::OutOfOfficeCheck)
              .to receive(:run) { |_, mail_hash| mail_hash[:'x-zammad-out-of-office'] = false }
          end

          it 're-opens a closed ticket' do
            expect { described_class.new.process({}, raw_mail) }
              .to not_change(Ticket, :count)
              .and change { ticket.reload.state.name }.to('open')
          end
        end

        context 'when OutOfOfficeCheck filter applies x-zammad-out-of-office: true' do
          before do
            allow(Channel::Filter::OutOfOfficeCheck)
              .to receive(:run) { |_, mail_hash| mail_hash[:'x-zammad-out-of-office'] = true }
          end

          it 'does not re-open a closed ticket' do
            expect { described_class.new.process({}, raw_mail) }
              .to not_change(Ticket, :count)
              .and not_change { ticket.reload.state.name }
          end
        end
      end
    end

    describe 'suppressing normal Ticket::Article callbacks' do
      context 'from sender: "Agent"' do
        let(:agent) { create(:agent) }

        it 'does not dispatch an email on article creation', :performs_jobs do
          expect do
            described_class.new.process({}, <<~RAW.chomp)
              From: #{agent.email}
              To: customer@example.com
              Subject: some subject

              Some Text
            RAW
          end.not_to have_enqueued_job(TicketArticleCommunicateEmailJob)
        end
      end
    end

    context 'when an unprocessable mail is received' do
      let(:parser)  { described_class.new }
      let(:channel) { {} }
      let(:from)    { 'Foo Bar <foo.bar@example.com>' }
      let(:mail)    { "From: #{from}\nTo: support@example.com\nSubject: Foo\n\nLorem ipsum dolor" }
      let(:error)   { Timeout::Error.new('execution expired') }
      let(:result)  { parser.process(channel, mail) }
      let(:ticket)  { result.first }
      let(:article) { result.second }

      before do
        allow(parser).to receive(:_process).and_raise(error)
      end

      it 'creates an error ticket and no failed email' do
        expect { result }
          .to change(Ticket, :count).by(1)
          .and not_change(FailedEmail, :count)
      end

      it 'returns the error ticket, its article and its customer' do
        expect(result).to eq([ticket, article, ticket.customer, nil])
      end

      it 'titles the ticket with a fixed text' do
        expect(ticket.title).to eq('Unprocessable email')
      end

      it 'creates the ticket as the system account and restores the current user' do
        agent = create(:agent)

        UserInfo.with_user_id(agent.id) do
          expect(ticket.created_by_id).to eq(1)
          expect(UserInfo.current_user_id).to eq(agent.id)
        end
      end

      it 'creates one internal article flagged as unprocessable' do
        expect(ticket.articles.reload).to contain_exactly(have_attributes(
                                                            internal:    true,
                                                            from:        from,
                                                            body:        'This ticket was created because the email could not be processed. The original email and the processing log are attached.',
                                                            type:        Ticket::Article::Type.lookup(name: 'note'),
                                                            sender:      Ticket::Article::Sender.lookup(name: 'System'),
                                                            preferences: include(email_unprocessable: true),
                                                          ))
      end

      it 'attaches the raw email and the processing log with their markers' do
        expect(article.attachments).to contain_exactly(
          have_attributes(filename: 'unprocessable_email.eml', content: mail, preferences: include('Mime-Type' => 'message/rfc822', 'email_unprocessable' => 'raw')),
          have_attributes(filename: 'processing_log.txt', content: include('Exception: Timeout::Error', 'Message: execution expired'), preferences: include('Mime-Type' => 'text/plain', 'email_unprocessable' => 'log')),
        )
      end

      context 'when the exception message carries bytes of an encoding that cannot be detected' do
        let(:error) { RuntimeError.new("can not parse |J\xFCrgen|".b) }

        before do
          allow(CharDet).to receive(:detect).and_return({ 'encoding' => nil, 'confidence' => 0 })
        end

        it 'still creates the error ticket and logs the message as far as it can be read' do
          expect { result }.to change(Ticket, :count).by(1)

          processing_log = article.attachments.find { |attachment| attachment.preferences['email_unprocessable'] == 'log' }.content

          expect(processing_log).to include('Exception: RuntimeError', 'Message: can not parse |J?rgen|')
        end
      end

      context 'when the mail carries a Message-ID' do
        let(:mail) { "From: #{from}\nMessage-ID: <error-1@example.com>\nSubject: Foo\n\nLorem ipsum dolor" }

        it 'stores it on the article, so that the mail is skipped when it is fetched again' do
          expect(article.message_id).to eq('<error-1@example.com>')

          validator = Channel::Driver::BaseEmailInbound::MessageValidator.new({ 'Message-ID' => '<error-1@example.com>' })

          expect(validator.already_imported?(true, channel)).to be(true)
        end
      end

      context 'when the system language is German' do
        before do
          create(:translation, locale: 'de-de', source: 'Unprocessable email', target: 'Nicht verarbeitbare E-Mail')
          Setting.set('locale_default', 'de-de')
        end

        it 'titles the ticket in German and keeps the title when the system language changes' do
          expect(ticket.title).to eq('Nicht verarbeitbare E-Mail')

          Setting.set('locale_default', 'en-us')

          expect(ticket.reload.title).to eq('Nicht verarbeitbare E-Mail')
        end
      end

      describe 'picking the group' do
        let!(:fallback_group) { Group.where(active: true).reorder(id: :asc).first }

        context 'when the channel has a group' do
          let(:group)   { create(:group) }
          let(:channel) { create(:email_channel, group:) }

          it 'uses the group of the channel' do
            expect(ticket).to have_attributes(group: group, preferences: include(channel_id: channel.id))
          end
        end

        context 'when the mail is delivered without a channel' do
          it 'falls back to the first active group' do
            expect(ticket.group).to eq(fallback_group)
          end
        end
      end

      describe 'identifying the customer' do
        context 'when the sender is an existing user' do
          let!(:user) { create(:customer, email: 'foo.bar@example.com') }

          it 'uses that user' do
            expect(ticket.customer).to eq(user)
          end
        end

        context 'when the sender has a name and an address' do
          it 'creates a customer with that name, the address as login and no email' do
            expect(ticket.customer).to have_attributes(firstname: 'Foo', lastname: 'Bar', login: 'foo.bar@example.com', email: '')
          end

          it 'assigns a later error ticket to the same customer' do
            first_customer = ticket.customer

            expect(described_class.new.tap { |p| allow(p).to receive(:_process).and_raise(error) }.process({}, mail).third)
              .to eq(first_customer)
          end
        end

        context 'when the sender is only an address' do
          let(:from) { 'foo.bar@example.com' }

          it 'creates a customer with the address as login and first name' do
            expect(ticket.customer).to have_attributes(firstname: 'foo.bar@example.com', login: 'foo.bar@example.com', email: '')
          end
        end

        context 'when the sender is no address' do
          let(:from) { 'Undisclosed' }

          it 'creates a customer with the value as login and first name' do
            expect(ticket.customer).to have_attributes(firstname: 'Undisclosed', login: 'undisclosed', email: '')
          end
        end

        context 'when the sender name is RFC 2047 encoded' do
          let(:from) { '=?UTF-8?B?SsO8cmdlbiBNw7xsbGVy?= <juergen@example.com>' }

          it 'decodes the name for the customer and the article' do
            expect(ticket.customer).to have_attributes(firstname: 'Jürgen', lastname: 'Müller', login: 'juergen@example.com')
            expect(article.from).to eq('"Jürgen Müller" <juergen@example.com>')
          end
        end

        context 'when the sender is an empty group' do
          let(:from) { 'undisclosed-recipients:;' }

          it 'assigns the system account without creating a user' do
            expect { result }.not_to change { User.where.not(id: 1).count }
            expect(ticket.customer_id).to eq(1)
          end
        end

        context 'when the mail has no sender' do
          let(:mail) { "To: support@example.com\nSubject: Foo\n\nLorem ipsum dolor" }

          it 'assigns the system account without creating a user' do
            expect { result }.not_to change { User.where.not(id: 1).count }
            expect(ticket.customer_id).to eq(1)
          end
        end

        context 'when the mail has no From but another sender field' do
          let(:mail) { "Sender: ops@example.com\nTo: support@example.com\nSubject: Foo\n\nLorem ipsum dolor" }

          it 'creates the customer from that field, as regular processing would' do
            expect(ticket.customer).to have_attributes(login: 'ops@example.com', firstname: 'ops@example.com', email: '')
            expect(article.from).to be_nil
          end
        end

        context 'when the customer cannot be created' do
          before do
            allow(Channel::Filter::BaseIdentifyUser).to receive(:user_create_without_email).and_raise(ActiveRecord::RecordInvalid)
          end

          it 'falls back to the system account' do
            expect(ticket.customer_id).to eq(1)
          end
        end

        context 'when the customer insert fails on the database' do
          # The login is cut to the column length on save, after the uniqueness
          #   validation compared the full address, so the insert hits the unique index.
          let(:from) { "#{'a' * 300}@example.com" }

          before { create(:customer, login: 'a' * 255) }

          it 'falls back to the system account' do
            expect(ticket.customer_id).to eq(1)
          end
        end
      end

      context 'when the error ticket cannot be created either' do
        before do
          allow_any_instance_of(Channel::EmailParser::ErrorTicket).to receive(:create!).and_raise('database gone')
        end

        it 'raises so that the mail stays on the server' do
          expect { result }.to raise_error(RuntimeError, 'database gone')
        end
      end

      context 'when the ticket of the error ticket cannot be created' do
        before do
          allow(Ticket).to receive(:create!).and_raise(ActiveRecord::RecordInvalid)
        end

        it 'leaves no customer behind' do
          expect { result }
            .to raise_error(ActiveRecord::RecordInvalid)
            .and not_change(User, :count)
        end
      end

      context 'when creating the error ticket exceeds the time limit' do
        # Without database work inside the limit: an interrupt during a statement breaks the transaction instead.
        before do
          stub_const('Channel::EmailParser::PROCESS_TIME_MAX', 0.1)
          allow_any_instance_of(Channel::EmailParser::ErrorTicket).to receive(:create!) { sleep 1 }
        end

        it 'raises so that the mail stays on the server' do
          expect { result }.to raise_error(Timeout::Error)
        end
      end
    end

    context 'when the input is no mail at all' do
      let(:input) { attributes_for(:failed_email, :invalid)[:data] }

      it 'creates an error ticket for the system account with the input and the reason attached' do
        ticket, article, = described_class.new.process({}, input)

        expect(ticket).to have_attributes(title: 'Unprocessable email', customer_id: 1)
        expect(article.attachments).to contain_exactly(
          have_attributes(filename: 'unprocessable_email.eml', content: input),
          have_attributes(filename: 'processing_log.txt', content: include('Exception: Exceptions::MissingAttribute', 'Message: Could not find any header field in the email.')),
        )
      end
    end

    context 'when processing fails after the mail became a ticket' do
      let(:raw_mail) { "From: foo@example.com\nTo: support@example.com\nSubject: Foo\n\nLorem ipsum dolor" }

      before do
        create(:trigger,
               condition: { 'ticket.action' => { 'operator' => 'is', 'value' => 'create' } },
               perform:   { 'ticket.action' => { 'value' => 'delete' } })
      end

      it 'creates no error ticket for the mail' do
        expect { described_class.new.process({}, raw_mail) }
          .to not_change(Ticket, :count)
          .and not_change(FailedEmail, :count)
      end

      it 'returns the ticket the mail became' do
        ticket, = described_class.new.process({}, raw_mail)

        expect(ticket.title).to eq('Foo')
      end
    end

    context 'when processing a sample mail fails on its own' do
      let(:mail_file)      { Rails.root.join('test/data/mail/mail038.box') }
      let(:mail)           { File.read(mail_file) }
      let(:result)         { described_class.new.process({}, mail) }
      let(:raw_email)      { result.second.attachments.find { |attachment| attachment.preferences['email_unprocessable'] == 'raw' }.content }
      let(:processing_log) { result.second.attachments.find { |attachment| attachment.preferences['email_unprocessable'] == 'log' }.content }

      # The time limit itself is covered by #process_with_timeout: a shortened PROCESS_TIME_MAX
      #   would also cut off the error ticket creation on a slow runner.
      context 'when a filter runs into a timeout' do
        before do
          allow(Channel::Filter::Trusted).to receive(:run).and_raise(Timeout::Error, 'execution expired')
        end

        it 'creates an error ticket with the sample mail, logging the timeout' do
          expect(result.first.title).to eq('Unprocessable email')
          expect(raw_email.b).to eq(File.binread(mail_file))
          expect(processing_log).to include('Exception: Timeout::Error')
        end
      end

      context 'when the content cannot be parsed' do
        before do
          freeze_time
          allow_any_instance_of(Channel::EmailParser::MessageWalker).to receive(:process_message_body).and_raise(ArgumentError, 'invalid byte sequence in UTF-8')
        end

        it 'creates an error ticket with the sample mail as it was received' do
          expect(result.first.title).to eq('Unprocessable email')
          expect(raw_email.b).to eq(File.binread(mail_file))
        end

        it 'logs the failure time, the exception and its backtrace' do
          expect(processing_log.lines.first(3)).to eq([
                                                        "Failed at: #{Time.zone.now.iso8601}\n",
                                                        "Exception: ArgumentError\n",
                                                        "Message: invalid byte sequence in UTF-8\n",
                                                      ])
          expect(processing_log).to include('app/models/channel/email_parser/content_parser.rb')
            .and include('app/models/channel/email_parser.rb')
        end
      end
    end
  end

  describe '#process_with_timeout' do
    let(:parser) { described_class.new }

    before do
      stub_const('Channel::EmailParser::PROCESS_TIME_MAX', 0.1)
      allow(parser).to receive(:_process) { sleep 1 }
    end

    it 'stops processing that exceeds the time limit' do
      expect { parser.process_with_timeout({}, 'mail') }.to raise_error(Timeout::Error)
    end
  end

  describe '#process_oversized_mail' do
    let(:channel)           { create(:email_channel) }
    let(:raw_incoming_mail) { "From: #{from}\nTo: support@example.com\nSubject: Foo\n\nLorem ipsum dolor" }

    before do
      create(:email_address, channel:)
      allow(channel).to receive(:deliver)
    end

    context 'when the mail has a sender address' do
      let(:from) { 'foo@example.com' }

      it 'sends a postmaster reply' do
        described_class.new.process_oversized_mail(channel, raw_incoming_mail)

        expect(channel).to have_received(:deliver).with(include(to: 'foo@example.com'))
      end
    end

    context 'when the sender address is empty' do
      let(:from) { '<>' }

      it 'sends no postmaster reply' do
        described_class.new.process_oversized_mail(channel, raw_incoming_mail)

        expect(channel).not_to have_received(:deliver)
      end
    end

    context 'when the mail has no sender field at all' do
      let(:raw_incoming_mail) { "To: support@example.com\nSubject: Foo\n\nLorem ipsum dolor" }

      it 'skips the postmaster reply without logging an error' do
        allow(Rails.logger).to receive(:info)
        allow(Rails.logger).to receive(:error)

        described_class.new.process_oversized_mail(channel, raw_incoming_mail)

        expect(channel).not_to have_received(:deliver)
        expect(Rails.logger).to have_received(:info).with('Mail too large has no sender address. Skipping postmaster reply.')
        expect(Rails.logger).not_to have_received(:error)
      end
    end
  end

  describe '#compose_postmaster_reply' do
    let(:raw_incoming_mail) { Rails.root.join('test/data/mail/mail010.box').read }

    shared_examples 'postmaster reply' do
      it 'composes postmaster reply' do
        reply = described_class.new.send(:compose_postmaster_reply, raw_incoming_mail, locale)
        expect(reply[:to]).to eq('smith@example.com')
        expect(reply[:content_type]).to eq('text/plain')
        expect(reply[:subject]).to eq(expected_subject)
        expect(reply[:body]).to eq(expected_body)
      end
    end

    context 'for English locale (en)' do
      include_examples 'postmaster reply' do
        let(:locale)           { 'en' }
        let(:expected_subject) { '[undeliverable] Message too large' }
        let(:expected_body) do
          body = <<~BODY
            Dear Smith Sepp,

            Unfortunately your email titled "Gruß aus Oberalteich" could not be delivered to one or more recipients.

            Your message was 0.01 MB but we only accept messages up to 10 MB.

            Please reduce the message size and try again. Thank you for your understanding.

            Regretfully,

            Postmaster of zammad.example.com
          BODY
          body.gsub(%r{\n}, "\r\n")
        end
      end
    end

    context 'for German locale (de)' do
      include_examples 'postmaster reply' do
        let(:locale) { 'de' }
        let(:expected_subject) { '[Unzustellbar] Nachricht zu groß' }
        let(:expected_body) do
          body = <<~BODY
            Hallo Smith Sepp,

            Ihre E-Mail mit dem Betreff "Gruß aus Oberalteich" konnte leider nicht an einen oder mehrere Empfänger zugestellt werden.

            Die Nachricht hatte eine Größe von 0.01 MB, wir akzeptieren jedoch nur E-Mails mit einer Größe von bis zu 10 MB.

            Bitte reduzieren Sie die Größe Ihrer Nachricht und versuchen Sie es erneut. Vielen Dank für Ihr Verständnis.

            Mit freundlichen Grüßen

            Postmaster von zammad.example.com
          BODY
          body.gsub(%r{\n}, "\r\n")
        end
      end
    end
  end

  describe '#mail_to_group' do

    context 'when EmailAddress exists' do

      context 'when gives address matches exactly' do

        let(:group) { create(:group) }
        let(:channel)        { create(:email_channel, group: group) }
        let!(:email_address) { create(:email_address, channel: channel) }

        it 'returns the Channel Group' do
          expect(described_class.mail_to_group(email_address.email)).to eq(group)
        end
      end

      context 'when gives address matches key insensitive' do

        let(:group) { create(:group) }
        let(:channel)        { create(:email_channel, group: group) }
        let(:address)        { 'KeyInsensitive@example.COM' }
        let!(:email_address) { create(:email_address, email: address, channel: channel) }

        it 'returns the Channel Group' do
          expect(described_class.mail_to_group(address)).to eq(group)
        end
      end

      context 'when no Channel is assigned' do

        let!(:email_address) { create(:email_address, channel: nil) }

        it 'returns nil' do
          expect(described_class.mail_to_group(email_address.email)).to be_nil
        end
      end

      context 'when Channel has no Group assigned' do

        let(:channel)        { create(:email_channel, group: nil) }
        let!(:email_address) { create(:email_address, channel: channel) }

        it 'returns nil' do
          expect(described_class.mail_to_group(email_address.email)).to be_nil
        end
      end
    end

    context 'when given address is not parse-able' do

      let(:address) { 'this_is_not_a_valid_email_address' }

      it 'returns nil' do
        expect(described_class.mail_to_group(address)).to be_nil
      end
    end
  end

  describe 'Updating group settings causes huge numbers of delayed jobs #4306', searchindex: true do
    let(:new_email) { <<~RAW.chomp }
      From: Max Smith <customer@example.com>
      To: myzammad@example.com
      Subject: test sender name update 2

      Some Text
    RAW

    it 'does create search index jobs for new email tickets' do
      ticket, = described_class.new.process({}, new_email)
      job = Delayed::Job.all.detect { |row| YAML.load(row.handler, permitted_classes: [ActiveJob::QueueAdapters::DelayedJobAdapter::JobWrapper]).job_data['arguments'] == ['Ticket', ticket.id] }
      expect(job).to be_present
    end
  end

  # https://github.com/zammad/zammad/issues/5227
  describe 'decodes and trims base64/encoded email subject' do
    context 'for a subject with encoded whitespace' do

      let(:raw_mail) { <<~RAW.chomp }
        From: sender@example.com
        To: recipient@example.com
        Subject: =?UTF-8?B?ICAgICAgVGVzdCBFbWFpbCBTdWJqZWN0ICAg?=

        Body text
      RAW

      let(:parsed)           { described_class.new.parse(raw_mail) }
      let(:expected_subject) { 'Test Email Subject' }

      it 'decodes and trims the subject correctly' do
        expect(parsed[:subject]).to eq(expected_subject)
      end
    end
  end
end
