Prevent ActionMailer from sending to deleted users / blacklisted addresses

No need to check in normal code, just do everything as usual and this interceptor will prevent you from spamming people who do not want any emails.
Its not perfect(missing bc/bcc filters but if should be fine for 90% of cases)

#config/initializers/blacklisted_emails.rb
class MailInterceptor
  def self.delivering_email(message)
    if User.where(:email => message.to, :receive_emails => false).any?
      message.perform_deliveries = false
    end
  end
end

Mail.register_interceptor(MailInterceptor)
Advertisements

One thought on “Prevent ActionMailer from sending to deleted users / blacklisted addresses

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s