Nope, this website is not dead, I was only -as usual- too lazy to keep it updated. Well, I just wanted to post a little something to check your IMAP accounts for unread mails with Ruby.
Unfortunately, it requires ruby 1.9 (btw, this is a good reason to give it a try). I'm not fluent enough to take advantage of any new features, but the Net::IMAP modules has been updated and supports a lot more authentication schemes than in 1.8.
Enough blah, here is the code:
#!/usr/bin/ruby1.9 accounts = [{ :name => 'example', :server => 'imap.example', :username => 'me@example.com', :password => 'mypass', :method => 'PLAIN', :mailboxes => ["INBOX"] }] require 'net/imap' def check_mails(account) imap = Net::IMAP.new(account[:server]) imap.authenticate(account[:method], account[:username], account[:password]) print "#{account[:name].capitalize}: " account[:mailboxes].each do |mailbox| imap.examine(mailbox) unread = 0 imap.search(["UNSEEN"]).each do |message_id| unread += 1 end status = imap.status(mailbox, ["MESSAGES"]) print "#{mailbox.capitalize} #{unread}/#{status["MESSAGES"]} " imap.disconnect end end accounts.each { |a| check_mails(a) }
First, we define an array of hashes representing the IMAP accounts with their parameters (the keys speak for themselves).
Then we require the Net::IMAP module and define a method to check the mails.
The connexion and authentication parts are obvious.
We then loop on each defined mailbox and EXAMINE it, which will select it in read-only mode, allowing us to search messages.
The status method used later allow us to get some informations such as the RECENT and total messages counts. Unfortunately, we can't trust the RECENT count, because it's reset at every connexion, and I wanted the unread count.
That's why we have to search the messages having the UNSEEN flag set and loop on them.
We then ask for the status of the mailbox as explained before and print the results.
Finally, we we loop on the accounts and call the method.
So this is it, that's all for today (and my WMII status bar is happier! :).
Discussion