Avoid Emailing Bounced Addresses
Wednesday, September 12th, 2007In the last post, I explained how I use VERP to handle email bounces and mark bad email addresses. I use email addresses as login handles, so I can’t just delete accounts with email addresses that have become invalid. However, I still want to avoid sending emails to addresses with permanent failures. The address verification needs to happen in one central location before emails are sent. There are numerous actions on the site that trigger notification emails, and I don’t want to every programmer to have to remember to check the status of an email address before sending an email.
I aliased the perform_delivery_sendmail() method in ActionMailer to my own gatekeeper method that checks the status of the recipient address before sending an email. Email is my own ActiveRecord model that stores the status of each address. Here’s the code, which I placed in a file called email_gatekeeper.rb in the lib directory of my Rails project:
module ActionMailer
class Base
private
def perform_delivery_sendmail_with_gatekeeper(mail)
ignore = false
if (mail.to.size() == 1)
email_address = Email.find_by_address(mail.to[0])
if (email_address && (email_address.status == Email::BOUNCED))
ignore = true
end
end
perform_delivery_sendmail_without_gatekeeper(mail) unless (ignore)
end
alias_method_chain :perform_delivery_sendmail, :gatekeeper
end
end