FEATURE: Skip sending emails to domains on the `.invalid` TLD (#7162)

FEATURE: Skip sending emails to domains on the .invalid TLD (#7162)

This is a reserved TLD which we use when importing users without an email address. RFC 2606 - Reserved Top Level DNS Names

diff --git a/app/models/skipped_email_log.rb b/app/models/skipped_email_log.rb
index 3e73b58..0fc28fa 100644
--- a/app/models/skipped_email_log.rb
+++ b/app/models/skipped_email_log.rb
@@ -32,7 +32,8 @@ class SkippedEmailLog < ActiveRecord::Base
       sender_message_to_blank: 17,
       sender_text_part_body_blank: 18,
       sender_body_blank: 19,
-      sender_post_deleted: 20
+      sender_post_deleted: 20,
+      sender_message_to_invalid: 21
       # you need to add the reason in server.en.yml below the "skipped_email_log" key
       # when you add a new enum value
     )
diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml
index c1cba64..7c40397 100644
--- a/config/locales/server.en.yml
+++ b/config/locales/server.en.yml
@@ -3465,6 +3465,7 @@ en:
     sender_text_part_body_blank: "text_part.body is blank"
     sender_body_blank: "body is blank"
     sender_post_deleted: "post has been deleted"
+    sender_message_to_invalid: "recipient has invalid email address"
 
   color_schemes:
     base_theme_name: "Base"
diff --git a/lib/email/sender.rb b/lib/email/sender.rb
index 40217f3..b8c62eb 100644
--- a/lib/email/sender.rb
+++ b/lib/email/sender.rb
@@ -35,6 +35,8 @@ module Email
       return skip(SkippedEmailLog.reason_types[:sender_message_blank])    if @message.blank?
       return skip(SkippedEmailLog.reason_types[:sender_message_to_blank]) if @message.to.blank?
 
+      return skip(SkippedEmailLog.reason_types[:sender_message_to_invalid]) if to_address.end_with?(".invalid")
+
       if @message.text_part
         if @message.text_part.body.to_s.blank?
           return skip(SkippedEmailLog.reason_types[:sender_text_part_body_blank])
diff --git a/spec/components/email/sender_spec.rb b/spec/components/email/sender_spec.rb
index 472edab..5cd476a 100644
--- a/spec/components/email/sender_spec.rb
+++ b/spec/components/email/sender_spec.rb
@@ -58,6 +58,13 @@ describe Email::Sender do
     Email::Sender.new(message, :hello).send
   end
 
+  it "doesn't deliver when the to address uses the .invalid tld" do
+    message = Mail::Message.new(body: 'hello', to: 'myemail@example.invalid')
+    message.expects(:deliver_now).never
+    expect { Email::Sender.new(message, :hello).send }.
+      to change { SkippedEmailLog.where(reason_type: SkippedEmailLog.reason_types[:sender_message_to_invalid]).count }.by(1)
+  end
+
   it "doesn't deliver when the body is nil" do
     message = Mail::Message.new(to: 'eviltrout@test.domain')
     message.expects(:deliver_now).never

GitHub sha: 420c6f81

1 Like

This commit has been mentioned on Discourse Meta. There might be relevant details there: