Mail Fetcher - Fetch Email from Ruby and Rails

I recently had to write something to fetch emails from a GMail account and process the emails to check if the email was a bounce (bad email address). If so, the person in the system associated with the bounced email would be deleted from the database. I did some searching for such thing and found this:

How to receive emails with Rails

About half way down the page you see an example for polling emails from a POP3 server (edited for space):
require 'net/pop'
require File.dirname(__FILE__) + '/../config/environment'

logger = RAILS_DEFAULT_LOGGER

logger.info "Running Mail Importer..." 
Net::POP3.start("mail.server.net", nil, "username", "password") do |pop|
  if pop.mails.empty?
    logger.info "NO MAIL" 
  else
    pop.mails.each do |email|

      begin
        logger.info "receiving mail..." 
        Mailman.receive(TMail::Mail.parse(email.pop))
        email.delete
      rescue Exception => e
        logger.error e.message
      end

    end
  end
end
logger.info "Finished Mail Importer."

So try this with a GMail server and you get no connection. Why? Because Google uses SSL when logging in via POP3. So the I looked around and found someone using SSL to login via POP3. All they did was add this line right before trying to start the connection: Net::POP3.enable_ssl(OpenSSL::SSL::VERIFY_NONE)

Simple enough. I went ahead and tried that, and it blows up with the following error: undefined method `enable_ssl' for Net::POP3:Class. Now trying to find out why this didn't work was annoying, but I finally found out that in the current version of Ruby (1.8.6), Net::POP3 doesn't understand enable_ssl. The edge version, however, does. So, I got the net/pop.rb file and required it instead of the 1.8.6 version and voila! It works! So, instead of just posting this and letting everyone know that you have to do this to make SSL POP3 access work, I made a plugin:

Mail Fetcher

Now the whole world may enjoy SSL POP3 access to their hearts' content. And, it also works with IMAP. Checkout the README and mail_fetcher.rb to get all the details. Enjoy!

Update: You can now access this plugin in all it's git-ty glory!

Posted by Steve on Sunday, February 17, 2008