I’m a super-novice with Ruby, and playing around with the IMAP library. The below program seems to work but it goes on forever until all messages are loaded. How would I limit the output to an X number of messages, like if I only wanted to show 10? I imagine it’s some sort of “if envelope =” — but don’t know what to put there. Thanks!
require 'net/imap'
imap = Net::IMAP.new('mail.domain.com')
imap.authenticate('LOGIN', ' ', ' ')
imap.examine('INBOX')
imap.search(["SEEN"]).each do |message_id|
envelope = imap.fetch(message_id, "ENVELOPE")[0].attr["ENVELOPE"]
puts "#{envelope.from[0].name}: \t#{envelope.subject}"
end
Not sure if appropriate here or if I should make a new question, but using the “SINCE” idea from below, how would I display a count of all the emails (elements in the array) fetched?
imap.examine('INBOX')
imap.search(["SINCE", "17-Feb-2012"]).each do |message_id|
envelope = imap.fetch(message_id, "ENVELOPE")[0].attr["ENVELOPE"]
puts "#{envelope.from[0].name}: \t#{envelope.subject}"
puts "#{envelope.count}"
end
The above puts the number 10 after every line, regardless of the amount of emails returned. How would I a) only put the result at the end of all the emails listed and b) find a true count of the elements in the array?
OK, figured out the second part:
require 'net/imap'
imap = Net::IMAP.new('mail.domain.com')
imap.authenticate('LOGIN', 'username', 'password')
imap.examine('INBOX')
mail_count = imap.search(["SINCE", "20-Feb-2012"])
puts mail_count.count
You can use
sliceto get only N results:The first parameter (here is 0) specified the start position, and the second the total number you need.
Note: based on IMAP’s search method’s implementation, the underlying calling might still fetch all messages from the server.