Sunday, January 13, 2008

RubyGarden Archives: Scripting Outlook

Editor's Note: Once upon a time, there was a website named, which contained many helpful links and articles. The website has recently dropped off the face of the earth. The following "Scripting Outlook" article was salvaged from the Google cache and is provided here in its entirety.

With some help of the the ScriptingExcel page and the Office helpfiles mentioned there a short script to list your Outlook messages. The script should be pretty easy to expand. One method that was really helpfull in figuring out what is possible is:



require 'win32ole'

myApp = WIN32OLE::new("outlook.Application")

# load Outlook OLE constants

class OutlookConst

WIN32OLE.const_load(myApp, OutlookConst)

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

ns = myApp.GetNameSpace("MAPI")
#ns.Logon # uncomment for online usage
folders = ns.Folders

new_messages = 0

folders.each {
| folder |
puts "+" + folder.Name

folder.Folders.each {
| folder |
# puts " " + folder.Name
if ["Inbox","Sent Items"].member? folder.Name
folder.Items.each {
| msg |
if msg['UnRead']
new_messages += 1
puts " From: " + msg['SenderName']
puts " Subject: " + msg['Subject']

puts " Unable to open"
puts "You have #{new_messages} new message(s)"

Glauber 2003-10-09:

* Here's a quick tip that would have saved me some time: When iterating over a list of Outlook items (e.g.: MailItems) in order to move or delete some of them, you must do so backwards (GetLast... GetPrevious... GetPrevious...). In other words, don't attempt to access an item that's after the one you deleted or moved.
* Here's another tip: there's no good way to find the From Internet email address of a message. Most times, creating a reply and extracting the first recipient for it will work, but sometimes not (it may give you an Exchange X.400 address instead of what you're looking for). Don't send the reply, discard it.

1 comment:

echristopherson said...

It looks like nowadays you have to use msg.UnRead instead of msg['UnRead'] (etc.)

Also, I'm unable to get it to list more than 30 messages. I get:
"WIN32OLERuntimeError: (in OLE method `SenderName': )
OLE error code:4096 in Microsoft Office Outlook
Your server administrator has limited the number of items you can open simultaneously. Try closing messages you have opened or removing attachments and images from unsent messages you are composing.
HRESULT error code:0x80020009"

I've tried closing each message with msg.Close(OutlookConst::OlDiscard), but it doesn't work. Is there something else I should do to list more than 30?