Post Office Protocol 3 (POP3) is the most popular protocol used to retrieve e-mail from a mail server. If you’re using an e-mail program that’s installed on your computer (as opposed to webmail, such as HotMail or Yahoo! Mail) it probably uses the POP3 protocol to communicate with the mail server that receives your mail from the outside world.
With Ruby it’s possible to use the net/pop library to do the same things that youre-mail client can, such as preview, retrieve, or delete mail. If you were feeling creative,you could even use net/pop to develop your own anti-spam tools.

■ Note In this section our examples won’t run without adjustments, as they need to operate on a real mail account. If you wish to run them, you would need to replace the server name, username, and passwords
with those of a POP3/mail account that you have access to. Ideally, you’ll be able to create a test e-mail account if you want to play with the examples here, or have a backup of your mail first, in case of unforeseen errors. That’s because although you cannot delete mail directly from your local e-mail program, you might delete any new mail waiting on your mail server. Once you’re confident of your code and what you want to achieve, then you change your settings to work upon a live account.

The basic operations you can perform with a POP3 server are to connect to it, receive
information about the mail an account contains, view that mail, delete the mail, and disconnect. First, you’ll connect to a POP3 server to see if there are any messages available for download, and if so, how many:

require 'net/pop'
mail_server = Net::POP3.new('mail.mailservernamehere.com')
begin
  mail_server.start('username','password')
  if mail_server.mails.empty?
    puts "No mails"
  else
    puts "#{mail_server.mails.length} mails waiting"
  end
rescue
  puts "Mail error"
end
Advertisements