FIX: Prioritize VERP key over final_recipient header in bounced email

FIX: Prioritize VERP key over final_recipient header in bounced email

Per RFC3464 2.3.2, the final_recipient header may not match the address we originally sent the email to.

diff --git a/lib/email/receiver.rb b/lib/email/receiver.rb
index 68a5fa8..2f5bc9c 100644
--- a/lib/email/receiver.rb
+++ b/lib/email/receiver.rb
@@ -513,13 +513,13 @@ module Email
     def parse_from_field(mail = nil)
       mail ||= @mail
 
-      if mail.bounced?
+      if email_log.present?
+        email = email_log.to_address || email_log.user&.email
+        return [email, email_log.user&.username]
+      elsif mail.bounced?
         Array.wrap(mail.final_recipient).each do |from|
           return extract_from_address_and_name(from)
         end
-      elsif email_log.present?
-        email = email_log.user&.email || email_log.to_address
-        return [email, email_log.user&.username]
       end
 
       return unless mail[:from]
diff --git a/spec/components/email/receiver_spec.rb b/spec/components/email/receiver_spec.rb
index d3a89ac..71d57a8 100644
--- a/spec/components/email/receiver_spec.rb
+++ b/spec/components/email/receiver_spec.rb
@@ -212,6 +212,14 @@ describe Email::Receiver do
       expect(email_log_2.bounced).to eq(true)
     end
 
+    it "works when the final recipient is different" do
+      expect { process(:verp_bounce_different_final_recipient) }.to raise_error(Email::Receiver::BouncedEmailError)
+
+      email_log.reload
+      expect(email_log.bounced).to eq(true)
+      expect(email_log.user.user_stat.bounce_score).to eq(SiteSetting.soft_bounce_score)
+    end
+
     it "sends a system message once they reach the 'bounce_score_threshold'" do
       expect(user.active).to eq(true)
 
diff --git a/spec/fixtures/emails/verp_bounce_different_final_recipient.eml b/spec/fixtures/emails/verp_bounce_different_final_recipient.eml
new file mode 100644
index 0000000..cc6e448
Binary files /dev/null and b/spec/fixtures/emails/verp_bounce_different_final_recipient.eml differ

GitHub sha: 0644c10b

2 Likes