Path: | net/pop.rb |
Last Update: | Sun Oct 05 17:23:37 GMT+10:00 2003 |
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).
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') {|f| f.write m.pop } m.delete i += 1 end puts "#{pop.mails.size} mails popped." end pop.finish # (3)
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') {|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') {|f| f.write m.pop } m.delete i += 1 end puts "#{pop.mails.size} mails popped." end }
POP3#delete_all alternates each_mail and m.delete.
require 'net/pop' Net::POP3.start('pop.example.com', 110, 'YourAccount', 'YourPassword') {|pop| if pop.mails.empty? puts 'no mail.' else i = 1 pop.delete_all do |m| File.open("inbox/#{i}", 'w') {|f| f.write m.pop } i += 1 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') {|f| f.write m.pop } i += 1 end
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') {|f| m.pop do |chunk| # get a message little by little. f.write chunk end i += 1 } end
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') {|pop| # Rest code is same. }
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') {|pop| pop.mails.select {|m| need_pop?(m.unique_id) }.each do |m| do_something(m.pop) 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.