Reading emails using POP3 in Ruby

By: James Edward Gray II Emailed: 1744 times Printed: 2432 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

This example retrieves messages from the server and deletes them on the server.

Messages are written to files named ‘inbox/1’, ‘inbox/2’, .… Replace ‘pop.example.com’ with your POP3 server address, and ‘YourAccount’ and ‘YourPassword’ with the appropriate account details.

    require 'net/pop'

    pop = Net::POP3.new('pop.example.com')
    pop.start('YourAccount', 'YourPassword')             # (1)
    if pop.mails.empty?
      puts 'No mail.'
    else
      i = 0
      pop.each_mail do |m|   # or "pop.mails.each ..."   # (2)
        File.open("inbox/#{i}", 'w') do |f|
          f.write m.pop
        end
        m.delete
        i += 1
      end
      puts "#{pop.mails.size} mails popped."
    end
    pop.finish                                           # (3)
  1. Call Net::POP3#start and start POP session.
  2. Access messages by using POP3#each_mail and/or POP3#mails.
  3. Close POP session by calling POP3#finish or use the block form of start.

Shortened Code

The example above is very verbose. You can shorten the code by using some utility methods. First, the block form of Net::POP3.start can be used instead of POP3.new, POP3#start and POP3#finish.

    require 'net/pop'

    Net::POP3.start('pop.example.com', 110,
                    'YourAccount', 'YourPassword') do |pop|
      if pop.mails.empty?
        puts 'No mail.'
      else
        i = 0
        pop.each_mail do |m|   # or "pop.mails.each ..."
          File.open("inbox/#{i}", 'w') do |f|
            f.write m.pop
          end
          m.delete
          i += 1
        end
        puts "#{pop.mails.size} mails popped."
      end
    end

POP3#delete_all is an alternative for each_mail and delete.

    require 'net/pop'

    Net::POP3.start('pop.example.com', 110,
                    'YourAccount', 'YourPassword') do |pop|
      if pop.mails.empty?
        puts 'No mail.'
      else
        i = 1
        pop.delete_all do |m|
          File.open("inbox/#{i}", 'w') do |f|
            f.write m.pop
          end
          i += 1
        end
      end
    end

And here is an even shorter example.

    require 'net/pop'

    i = 0
    Net::POP3.delete_all('pop.example.com', 110,
                         'YourAccount', 'YourPassword') do |m|
      File.open("inbox/#{i}", 'w') do |f|
        f.write m.pop
      end
      i += 1
    end

Memory Space Issues

All the examples above get each message as one big string. This example avoids this.

    require 'net/pop'

    i = 1
    Net::POP3.delete_all('pop.example.com', 110,
                         'YourAccount', 'YourPassword') do |m|
      File.open("inbox/#{i}", 'w') do |f|
        m.pop do |chunk|    # get a message little by little.
          f.write chunk
        end
        i += 1
      end
    end

Using APOP

The net/pop library supports APOP authentication. To use APOP, use the Net::APOP class instead of the Net::POP3 class. You can use the utility method, Net::POP3.APOP(). For example:

    require 'net/pop'

    # Use APOP authentication if $isapop == true
    pop = Net::POP3.APOP($is_apop).new('apop.example.com', 110)
    pop.start(YourAccount', 'YourPassword') do |pop|
      # Rest of the code is the same.
    end

Fetch Only Selected Mail Using ‘UIDL’ POP Command

If your POP server provides UIDL functionality, you can grab only selected mails from the POP server. e.g.

    def need_pop?( id )
      # determine if we need pop this mail...
    end

    Net::POP3.start('pop.example.com', 110,
                    'Your account', 'Your password') do |pop|
      pop.mails.select { |m| need_pop?(m.unique_id) }.each do |m|
        do_something(m.pop)
      end
    end

The POPMail#unique_id() method returns the unique-id of the message as a String. Normally the unique-id is a hash of the message.


Ruby Home | All Ruby Tutorials | Latest Ruby Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(0)


Be the first one to add a comment

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by James Edward Gray II
Using Forwardable in Ruby
Using Generator in Ruby
Using GServer in Ruby
Sending emails using SMTP in Ruby
Reading emails using POP3 in Ruby
IMAP in Ruby

More Tutorials in Ruby
Standard Library Packages in Ruby
Module Abbrev in Ruby
encoding and decoding in Ruby using Base64 Module
Benchmark module in Ruby
benchmark(caption = "", label_width = nil, fmtstr = nil, *labels) {|report| ...} in Ruby
bm(label_width = 0, *labels) {|report| ...} in Ruby
bmbm(width = 0) {|job| ...} in Ruby
CGI class in Ruby
URL encode a string in Ruby
escapeElement() in Ruby
escapeHTML() in Ruby
new(type = "query") in Ruby
parse(query) in Ruby
pretty() in Ruby
Format a Time object as a String in Ruby

More Latest News
Most Viewed Articles (in Ruby )
encoding and decoding in Ruby using Base64 Module
if . . . elsif . . . else in Ruby on rails
Using Proxy to connect to URLs in Ruby
Open and manipulate CSV files in Ruby
Reading emails using POP3 in Ruby
URL decode a string in Ruby
Defining tables and classes (using MySQL) in Ruby on Rails
Methods in Ruby on rails
Module Abbrev in Ruby
Benchmark module in Ruby
escapeHTML() in Ruby
new(type = "query") in Ruby
pretty() in Ruby
Reading URL content using Ruby (HTTP)
Sending emails using SMTP in Ruby
Most Emailed Articles (in Ruby)
if . . . elsif . . . else in Ruby on rails
Sending emails using SMTP in Ruby
encoding and decoding in Ruby using Base64 Module
bmbm(width = 0) {|job| ...} in Ruby
escapeHTML() in Ruby
Format a Time object as a String in Ruby
benchmark(caption = "", label_width = nil, fmtstr = nil, *labels) {|report| ...} in Ruby
bm(label_width = 0, *labels) {|report| ...} in Ruby
dRuby client/server mode sample program
Using Proxy to connect to URLs in Ruby
Using Observer in Ruby
Getting started with Ruby on rails
Prompts, Command Lines, Prompts, and irb in Ruby on rails
CGI class in Ruby
URL encode a string in Ruby