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 ).

4 comments:

  1. i follow the steps in the above post. but i cant get email in my application. so will u plz give me any reference links or some example programs for my references.

    ReplyDelete
  2. The code snippet given here is tested and it works.. can you tell me the error that came??

    ReplyDelete
    Replies
    1. Sorry to ask this basic question... but plz tell me where to write these codes ( I mean, which file / folder..)
      I am new to rails and really this blog was a bouncer (but it is exactly what I require)

      Delete
  3. I followed the steps and i am getting the following error:

    `rescue in rbuf_fill': Timeout::Error (Timeout::Error)

    It will be greate if you could help

    ReplyDelete