Some way to sort and paginate mails read from a POP3 mail se

Problem:

I have written a program to fetch mails from a POP3 mail server. I do
not parse all the mails at once, but i process a predefined number
based on page_size ( i could not find a simpler way of pagination), as
follows

def parseMail(page,pageSize)
emails=Array.new
#todo: open the connection only once, and iterate over the
mails, problem: connection to mail server closed
Net::POP3::start(MAIL_SERVER,nil,USER,PASS) do |pop|
if !pop.mails.empty?
mails=pop.mails
start=(page-1)*pageSize
last=start+pageSize
if (mails.length<last)
last=mails.length
end

          mails[start..(last-1)].each do|mail|
          begin
              email=TMail::Mail.parse(mail.pop)
              emails.push(email)
              rescue Exception => e
                  puts "Error receiving email at " + Time.now.to_s
  • "::: " + e.message
    raise e.message
    end
    end # end of the block
    end
    end

    return emails
    end

As you can see, i populate an array emails with the mails parsed. But
i want to sort the mails according to the date at which the mail was
sent. I want to parse the mails in the descending order of the mail’s
sent date. But pop.mails is an array of strings and i am not sure how
easily <=> operator can be implemented to order the mails this way.

Summary of the problem: A way to sort the mails read from a POP3
server, while not parsing all the mails.