Sunday, July 20, 2008

Ruby, Outlook and yield

How to get unread messages from outlook in Ruby.


require 'Outlook'

outlook = Outlook.new

#GET UNREAD MESSAGES FROM OUTLOOK
outlook.viewMessages(){|msg|
puts msg
}



require 'win32ole'
require 'date'
require "KeyStorage"

#Class MailItem value Object
class MailItem

def initialize(subj, to, from, cc, body, path, msgid, unread, created)
@subj = subj
@to = to
@from = from
@cc = cc
@body = body
@path = path
@msgid = msgid
@unread = unread
@created = created
#p msgid.length
end

attr_reader :subj, :to, :from, :cc, :body, :path, :msgid, :unread, :created

def eql?(o)
o.is_a?(MailItem) && msgid == o.msgid
end

def hash
@msgid.hash
end

def to_s
return "MailItem: @subj:" + @subj + "\n @to" + @to + "\n @cc " + @cc + "\n" + @msgid
end
end


class Outlook

OLFolderInbox = 6
OLMailItem = 43
OLAppointmentItem = 53

def initialize()
@ol = WIN32OLE.new("Outlook.Application")
puts "Get MAPI"
olookNameSpace = @ol.GetNameSpace("MAPI")
puts "Get default Inbox folder"
@loInbox = olookNameSpace.GetDefaultFolder(OLFolderInbox)
@unusedFolderPath = @loInbox.folderPath
end

def message2Item(loMailItem, folder)
case loMailItem.Class
when OLMailItem
MailItem.new(loMailItem.subject, loMailItem.to, loMailItem.senderName, loMailItem.cc, loMailItem.htmlBody, folder, loMailItem.entryID, loMailItem.UnRead, loMailItem.creationTime)
when OLAppointmentItem
#p "AppointmentItem found: [" + loMailItem.subject + "]"
MailItem.new(loMailItem.subject, "Appointment::", loMailItem.senderName, "", loMailItem.body, folder, loMailItem.entryID, loMailItem.UnRead, loMailItem.creationTime)
else
p "UnknownItem found: [" + loMailItem.subject + "]"
end
rescue Exception => e:
puts "Exception in message2Item: " + e
end

def processFolderWithSubs(folder, readAll)
fp = folder.folderPath.gsub(@unusedFolderPath, "").gsub("\\", "/")
#p "->" + fp
for loMailItem in folder.Items
if loMailItem.UnRead || readAll
messageItem = message2Item(loMailItem, fp)
if messageItem != nil
#call block with message
yield messageItem
end
end
end
#check subfolders
for loFolder in folder.Folders
processFolderWithSubs(loFolder, readAll){|m| yield m}
end
end

def viewMessages(readAll = false)
processFolderWithSubs(@loInbox, readAll){|m| yield m}
end

end