Tuesday, March 22, 2011

Installing Ruby 1.9.2 and Rails 3 stable on Ubuntu

There are a zillion threads on internet regarding fresh installation of ruby 1.9.2 and rails 3 on ubuntu, however, most of them have some sort of dependency missing. Lately, i found a very helpful link on this topic, so i thought of sharing the post

http://torqueo.net/installing-ruby-192-and-rails-3-stable-on-ubuntu/

Wednesday, March 16, 2011

Fetch emails from Gmail using POP3

There are a couple of protocols for fetching emails from email services such as Gmail.. POP and IMAP. In this post, i'll be telling a simple way of fetching emails from Gmail using POP3. The code is in Rails (will try to post a php version later if get time). The method is extremely simple and trivial. But before we jump to the code, the first thing you need to do is to enable POP access from your Gmail account. You can found the POP settings under "Settings" tab. Look at the below snapshot


Make sure that you save the changes. Now, we are done with the settings, let's see the code now.

for this code you need to have "net/pop".

require 'net/pop'

pop_server = 'pop.gmail.com'
pop_port = 995
username = "example@gmail.com"
password = "example_password"

Net::POP3.start(pop_server, pop_port, username, password) do |pop|
       if pop.mails.empty?
             puts "No Mail Found"
       else
             pop.mails.each do |email|
                  MailReader.receive(email.pop)
             end
       end
end

now, the only piece missing from the above code is "MailRead.receive". Basically, we need to have a email handler which has to be extended from ActionMailer. We just need to pass the email details to this handler and it will do the parsing for us. So, now let's see the code for this:

class MailReader < ActionMailer::Base
    def receive(email)
        puts "Subject ==>" + email.subject
        puts "Body ==> " + email.body
    end
end

That's all about it :) .. if you want to fetch and save attachments as well, just get the paperclip. You can download it from https://github.com/thoughtbot/paperclip (for direct installation with rails use the command rails plugin install git://github.com/thoughtbot/paperclip.git ).