diff --git a/app/mailboxes/imap/imap_mailbox.rb b/app/mailboxes/imap/imap_mailbox.rb index a8308b48a..01c8219bd 100644 --- a/app/mailboxes/imap/imap_mailbox.rb +++ b/app/mailboxes/imap/imap_mailbox.rb @@ -12,6 +12,9 @@ class Imap::ImapMailbox # prevent loop from chatwoot notification emails return if notification_email_from_chatwoot? + # Stop processing if email format doesn't match Chatwoot supported mail format + return unless email_from_valid_email? + ActiveRecord::Base.transaction do find_or_create_contact find_or_create_conversation @@ -34,6 +37,18 @@ class Imap::ImapMailbox @processed_mail = MailPresenter.new(@inbound_mail, @account) end + def email_from_valid_email? + Rails.logger.info("Processing Email from: #{@processed_mail.original_sender} : inbox #{@inbox.id}") + + # validate email with Devise.email_regexp + if Devise.email_regexp.match?(@processed_mail.original_sender) + true + else + Rails.logger.error("Email from: #{@processed_mail.original_sender} : inbox #{@inbox.id} is invalid") + false + end + end + def find_conversation_by_in_reply_to return if in_reply_to.blank? diff --git a/spec/mailboxes/imap/imap_mailbox_spec.rb b/spec/mailboxes/imap/imap_mailbox_spec.rb index 42942a548..5f2886b3d 100644 --- a/spec/mailboxes/imap/imap_mailbox_spec.rb +++ b/spec/mailboxes/imap/imap_mailbox_spec.rb @@ -54,6 +54,16 @@ RSpec.describe Imap::ImapMailbox do end end + context 'when a new email with invalid from' do + let(:inbound_mail) { create_inbound_email_from_mail(from: 'invalidemail', to: 'imap@gmail.com', subject: 'Hello!') } + + it 'does not create a new conversation' do + allow(Rails.logger).to receive(:error) + class_instance.process(inbound_mail.mail, channel) + expect(Rails.logger).to have_received(:error).with("Email from: invalidemail : inbox #{inbox.id} is invalid") + end + end + context 'when a reply for existing email conversation' do let(:prev_conversation) { create(:conversation, account: account, inbox: channel.inbox, assignee: agent) } let(:reply_mail) do