Created
June 1, 2013 20:56
-
-
Save comp615/5691718 to your computer and use it in GitHub Desktop.
If you send emails in Ruby on Rails using Gmail as your SMTP, this little rake task will locate all the bounced emails, and reset those users email addresses automatically for you. Emails will remain in your inbox, but will be marked as read once handled. You may want to customize this to do something else, or be more rigorous in which emails ar…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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