Access Gmail from Ruby using Net::POP3 and Stunnel
I Googled around for this at one point, however, all I could find were ill-fated attempts by a couple of tortured souls on ruby-talk. Google offers POP3S access to Gmail, but, unfortunately, Ruby’s Net::POP3S module is still under development. POP3S is the much reviled and revered Post Office Protocol tunneled over a thick blanket of SSL obfuscation. Fortunately, the good Stunnel folks have anticipated this kind of thing and they’re giving out some code that can encode and decode SSL to a standard socket.
This was done on OS X, but Stunnel seems to work on most platforms. However, I wasn’t finding it in ports or fink. So, I had to roll my own stunnel binary.
wget http://www.stunnel.org/download/stunnel/src/stunnel-3.22.tar.gz tar zxf stunnel-3.22.tar.gz cd stunnel-3.22 ./configure make sudo make install
Whew. So, after you’ve installed stunnel, you need to invoke it to redirect a local port to Google’s secure POP3 port located at pop.gmail.com on port 995. You can redirect any local port to Google’s pop server. I chose to use port 42 because that’s as good as anything else. Here’s my stunnel invocation.
sudo /usr/local/sbin/stunnel -c -d 42 -r pop.gmail.com:995
So, now you can use Ruby’s Net::POP3 to access your gmail from port 42 on your local machine. Stunnel will handle the details of SSL.
require 'net/pop'
pop = Net::POP3.new('localhost', 42)
pop.start('mrbeastly', 'sUp3Rs3kRiT!')
if pop.mails.empty?
puts 'No mail.'
else
i = 0
pop.each_mail do |m|
exit if i > 20
puts m.pop
i=i+1
end
end
Running this code will display the first 20 emails in Gmail to your terminal. This is really a stopgap solution until the fabled POP3S patch gets accepted into Ruby’s Net library. This is rumored to be soon. So, I’ll keep my hopes up.






