Skip to content

Instantly share code, notes, and snippets.

@deepakdargade
Forked from comp615/emails.rake
Created August 2, 2013 21:12
Show Gist options
  • Save deepakdargade/6143510 to your computer and use it in GitHub Desktop.
Save deepakdargade/6143510 to your computer and use it in GitHub Desktop.
desc "Log in to the Gmail account and cleanse anyone who appears to have bounced"
task :handle_bounces => :environment do
require 'gmail'
# Open a connection using your default smtp settings, could also define via YML or inline
gmail = Gmail.connect!(ActionMailer::Base.smtp_settings[:user_name], ActionMailer::Base.smtp_settings[:password])
# Find everything from the Gmail mailer daemon (unread only)
emails = gmail.inbox.emails(:unread, :from => "[email protected]", :subject => "Delivery Status Notification (Failure)")
Rails.logger.info("Found #{emails.length} messages")
emails.each do |email|
# Gmail sets a header "X-Failed-Recipients", with each email that failed
if !email.header["X-Failed-Recipients"].blank?
bad_addresses = email.header["X-Failed-Recipients"].value.split(",")
bad_addresses.each do |bad_addr|
Rails.logger.info("looking for user with email: #{bad_addr}")
# We assume you have a user model, but could also do whatever you want with the bad address here
user = User.find_by_email(bad_addr)
if user
Rails.logger.info("Found: #{user.name}, resetting email address")
user.email = nil # Reset the email, might vary for your use case
user.save
end
end # close emails form header
email.read! # Mark as read so we don't try to deal with it again next time
end
end # next email
gmail.logout # done!
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment