Class Net::POP3
In: lib/net/pop.rb
Parent: Protocol

Net::POP3

What is This Library?

This library provides functionality for retrieving email via POP3, the Post Office Protocol version 3. For details of POP3, see [RFC1939] (www.ietf.org/rfc/rfc1939.txt).

Examples

Retrieving Messages

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.

Methods

Constants

Revision = %q$Revision: 11708 $.split[1]

Attributes

address  [R]  The address to connect to.
open_timeout  [RW]  Seconds to wait until a connection is opened. If the POP3 object cannot open a connection within this time, it raises a TimeoutError exception.
port  [R]  The port number to connect to.
read_timeout  [R]  Seconds to wait until reading one block (by one read(1) call). If the POP3 object cannot complete a read() within this time, it raises a TimeoutError exception.

Public Class methods

Returns the APOP class if isapop is true; otherwise, returns the POP class. For example:

    # Example 1
    pop = Net::POP3::APOP($is_apop).new(addr, port)

    # Example 2
    Net::POP3::APOP($is_apop).start(addr, port) do |pop|
      ....
    end

[Source]

     # File lib/net/pop.rb, line 223
223:     def POP3.APOP( isapop )
224:       isapop ? APOP : POP3
225:     end

Opens a POP3 session, attempts authentication, and quits.

This method raises POPAuthenticationError if authentication fails.

Example: normal POP3

    Net::POP3.auth_only('pop.example.com', 110,
                        'YourAccount', 'YourPassword')

Example: APOP

    Net::POP3.auth_only('pop.example.com', 110,
                        'YourAccount', 'YourPassword', true)

[Source]

     # File lib/net/pop.rb, line 290
290:     def POP3.auth_only( address, port = nil,
291:                         account = nil, password = nil,
292:                         isapop = false )
293:       new(address, port, isapop).auth_only account, password
294:     end

The default port for POP3 connections, port 110

[Source]

     # File lib/net/pop.rb, line 200
200:     def POP3.default_port
201:       110
202:     end

Starts a POP3 session and deletes all messages on the server. If a block is given, each POPMail object is yielded to it before being deleted.

This method raises a POPAuthenticationError if authentication fails.

Example

    Net::POP3.delete_all('pop.example.com', 110,
                         'YourAccount', 'YourPassword') do |m|
      file.write m.pop
    end

[Source]

     # File lib/net/pop.rb, line 268
268:     def POP3.delete_all( address, port = nil,
269:                          account = nil, password = nil,
270:                          isapop = false, &block )
271:       start(address, port, account, password, isapop) {|pop|
272:         pop.delete_all(&block)
273:       }
274:     end

Starts a POP3 session and iterates over each POPMail object, yielding it to the block. This method is equivalent to:

    Net::POP3.start(address, port, account, password) do |pop|
      pop.each_mail do |m|
        yield m
      end
    end

This method raises a POPAuthenticationError if authentication fails.

Example

    Net::POP3.foreach('pop.example.com', 110,
                      'YourAccount', 'YourPassword') do |m|
      file.write m.pop
      m.delete if $DELETE
    end

[Source]

     # File lib/net/pop.rb, line 247
247:     def POP3.foreach( address, port = nil,
248:                       account = nil, password = nil,
249:                       isapop = false, &block )  # :yields: message
250:       start(address, port, account, password, isapop) {|pop|
251:         pop.each_mail(&block)
252:       }
253:     end

Creates a new POP3 object.

address is the hostname or ip address of your POP3 server.

The optional port is the port to connect to; it defaults to 110.

The optional isapop specifies whether this connection is going to use APOP authentication; it defaults to false.

This method does not open the TCP connection.

[Source]

     # File lib/net/pop.rb, line 342
342:     def initialize( addr, port = nil, isapop = false )
343:       @address = addr
344:       @port = port || self.class.default_port
345:       @apop = isapop
346: 
347:       @command = nil
348:       @socket = nil
349:       @started = false
350:       @open_timeout = 30
351:       @read_timeout = 60
352:       @debug_output = nil
353: 
354:       @mails = nil
355:       @n_mails = nil
356:       @n_bytes = nil
357:     end

Creates a new POP3 object and open the connection. Equivalent to

  Net::POP3.new(address, port, isapop).start(account, password)

If block is provided, yields the newly-opened POP3 object to it, and automatically closes it at the end of the session.

Example

   Net::POP3.start(addr, port, account, password) do |pop|
     pop.each_mail do |m|
       file.write m.pop
       m.delete
     end
   end

[Source]

     # File lib/net/pop.rb, line 326
326:     def POP3.start( address, port = nil,
327:                     account = nil, password = nil,
328:                     isapop = false, &block ) # :yield: pop
329:       new(address, port, isapop).start(account, password, &block)
330:     end

Public Instance methods

active?()

Alias for started?

Does this instance use APOP authentication?

[Source]

     # File lib/net/pop.rb, line 360
360:     def apop?
361:       @apop
362:     end

Starts a pop3 session, attempts authentication, and quits. This method must not be called while POP3 session is opened. This method raises POPAuthenticationError if authentication fails.

[Source]

     # File lib/net/pop.rb, line 299
299:     def auth_only( account, password )
300:       raise IOError, 'opening previously opened POP session' if started?
301:       start(account, password) {
302:         ;
303:       }
304:     end

Deletes all messages on the server.

If called with a block, yields each message in turn before deleting it.

Example

    n = 1
    pop.delete_all do |m|
      File.open("inbox/#{n}") do |f|
        f.write m.pop
      end
      n += 1
    end

This method raises a POPError if an error occurs.

[Source]

     # File lib/net/pop.rb, line 549
549:     def delete_all # :yield: message
550:       mails().each do |m|
551:         yield m if block_given?
552:         m.delete unless m.deleted?
553:       end
554:     end
each( )

Alias for each_mail

Yields each message to the passed-in block in turn. Equivalent to:

  pop3.mails.each do |popmail|
    ....
  end

This method raises a POPError if an error occurs.

[Source]

     # File lib/net/pop.rb, line 527
527:     def each_mail( &block )  # :yield: message
528:       mails().each(&block)
529:     end

Finishes a POP3 session and closes TCP connection.

[Source]

     # File lib/net/pop.rb, line 458
458:     def finish
459:       raise IOError, 'POP session not yet started' unless started?
460:       do_finish
461:     end

Provide human-readable stringification of class state.

[Source]

     # File lib/net/pop.rb, line 365
365:     def inspect
366:       "#<#{self.class} #{@address}:#{@port} open=#{@started}>"
367:     end

Returns an array of Net::POPMail objects, representing all the messages on the server. This array is renewed when the session restarts; otherwise, it is fetched from the server the first time this method is called (directly or indirectly) and cached.

This method raises a POPError if an error occurs.

[Source]

     # File lib/net/pop.rb, line 505
505:     def mails
506:       return @mails.dup if @mails
507:       if n_mails() == 0
508:         # some popd raises error for LIST on the empty mailbox.
509:         @mails = []
510:         return []
511:       end
512: 
513:       @mails = command().list.map {|num, size|
514:         POPMail.new(num, size, self, command())
515:       }
516:       @mails.dup
517:     end

Returns the total size in bytes of all the messages on the POP server.

[Source]

     # File lib/net/pop.rb, line 493
493:     def n_bytes
494:       return @n_bytes if @n_bytes
495:       @n_mails, @n_bytes = command().stat
496:       @n_bytes
497:     end

Returns the number of messages on the POP server.

[Source]

     # File lib/net/pop.rb, line 486
486:     def n_mails
487:       return @n_mails if @n_mails
488:       @n_mails, @n_bytes = command().stat
489:       @n_mails
490:     end

Set the read timeout.

[Source]

     # File lib/net/pop.rb, line 403
403:     def read_timeout=( sec )
404:       @command.socket.read_timeout = sec if @command
405:       @read_timeout = sec
406:     end

Resets the session. This clears all "deleted" marks from messages.

This method raises a POPError if an error occurs.

[Source]

     # File lib/net/pop.rb, line 559
559:     def reset
560:       command().rset
561:       mails().each do |m|
562:         m.instance_eval {
563:           @deleted = false
564:         }
565:       end
566:     end

WARNING: This method causes a serious security hole. Use this method only for debugging.

Set an output stream for debugging.

Example

  pop = Net::POP.new(addr, port)
  pop.set_debug_output $stderr
  pop.start(account, passwd) do |pop|
    ....
  end

[Source]

     # File lib/net/pop.rb, line 382
382:     def set_debug_output( arg )
383:       @debug_output = arg
384:     end

Starts a POP3 session.

When called with block, gives a POP3 object to the block and closes the session after block call finishes.

This method raises a POPAuthenticationError if authentication fails.

[Source]

     # File lib/net/pop.rb, line 421
421:     def start( account, password ) # :yield: pop
422:       raise IOError, 'POP session already started' if @started
423: 
424:       if block_given?
425:         begin
426:           do_start account, password
427:           return yield(self)
428:         ensure
429:           do_finish
430:         end
431:       else
432:         do_start account, password
433:         return self
434:       end
435:     end

true if the POP3 session has started.

[Source]

     # File lib/net/pop.rb, line 409
409:     def started?
410:       @started
411:     end

Private Instance methods

[Source]

     # File lib/net/pop.rb, line 474
474:     def command
475:       raise IOError, 'POP session not opened yet' \
476:                                       if not @socket or @socket.closed?
477:       @command
478:     end

[Source]

     # File lib/net/pop.rb, line 463
463:     def do_finish
464:       @mails = nil
465:       @command.quit if @command
466:     ensure
467:       @started = false
468:       @command = nil
469:       @socket.close if @socket and not @socket.closed?
470:       @socket = nil
471:     end

[Source]

     # File lib/net/pop.rb, line 437
437:     def do_start( account, password )
438:       @socket = self.class.socket_type.old_open(@address, @port,
439:                                    @open_timeout, @read_timeout, @debug_output)
440:       on_connect
441:       @command = POP3Command.new(@socket)
442:       if apop?
443:         @command.apop account, password
444:       else
445:         @command.auth account, password
446:       end
447:       @started = true
448:     ensure
449:       do_finish if not @started
450:     end

[Source]

     # File lib/net/pop.rb, line 453
453:     def on_connect
454:     end

[Validate]