Count Outlook Inbox Unread / Total From Ruby


Well, Track your unread items/total items count in Outlook on startup, except for the pesky Outlook Macro disabled security problem. Besides, I never restarted Outlook often enough for it to track much of anything.

Instead, I decided to create a Ruby script to track the count. I’ve left reference URLs and test notes in place in this script. Yes, I had to look up how to write a file in Ruby… It’s essentially my 4th programming language after C, Java, Perl, PHP… okay… let’s say it’s pretty deep on the list.

require 'win32ole'
outlook = WIN32OLE.new('Outlook.Application')
# http://rubyonwindows.blogspot.com/2007/07/automating-outlook-with-ruby-tasks.html
mapi = outlook.GetNameSpace('MAPI')
# http://msdn.microsoft.com/en-us/library/aa220100%28office.11%29.aspx
# olFolderCalendar
# olFolderContacts
# olFolderDeletedItems
# olFolderDrafts
# olFolderInbox
# olFolderJournal
# olFolderJunk
# olFolderNotes
# olFolderOutbox
# olFolderSentMail
# olFolderTasks
# olPublicFoldersAllPublicFolders
# olFolderConflicts
# olFolderLocalFailures
# olFolderServerFailures
# olFolderSyncIssues

# http://msdn.microsoft.com/en-us/library/aa210918%28v=office.11%29.aspx
# OLEObject.ole_methods

class OutlookConst
end
# http://rubyonwindows.blogspot.com/search/label/outlook
WIN32OLE.const_load(outlook, OutlookConst)

# p "OlFolderInbox = #{OutlookConst::OlFolderInbox}"

inbox = mapi.GetDefaultFolder(OutlookConst::OlFolderInbox)

new_messages = 0
total_messages = 0

inbox.Items.each {
	| msg |
	begin 
		if msg['UnRead']
			new_messages += 1
		end
		total_messages += 1
	rescue
		puts " Unable to open"
	end
}
puts "You have #{new_messages} new message(s)"
t = Time.now

line="#{t.strftime("%m/%d/%Y %I:%M:%S %p")},#{new_messages},#{total_messages}"

localname="#{ENV['USERPROFILE']}\My Documents\outlookunread.csv"

# http://snippets.dzone.com/posts/show/5051
File.open(localname, 'a') {|f| f.puts(line) }

Leave a Reply

%d bloggers like this: