Friday, September 2, 2011

Automating Outlook with Ruby: Saving Mail Messages To Files

I've talked in the past about managing mail messages in your Inbox, and about saving email attachments to your hard drive. A reader recently asked about saving a mail message as a file on your hard drive.

This can be done by calling the MailItem's SaveAs() method. This method takes two arguments. The first argument is a string indicating the full path and filename to which you want to save the message. The second argument is an integer that indicates the file type.

Let's look at a brief example that saves an Inbox message as an HTML file:

require 'win32ole'

olHTML = 5
outlook = WIN32OLE.connect("Outlook.Application")
mapi = outlook.GetNameSpace("MAPI")
inbox = mapi.GetDefaultFolder(6)
msg = inbox.Items(2)
msg.SaveAs('c:\temp\message.htm', olHTML)

Further details on the SaveAs() method can be found here.
A full list of valid file type values can be found here.

That's all for now. Questions? Comments? Suggestions? Post a comment or send me an email.

Thanks for stopping by!


Hyunoodle said...

This was a very useful post. Part of our marketing program involves creating outlook copies of our email promotions for our salespeople in a network folder. Automating this process saved a lot of time! Thanks!

Anonymous said...

Just a word of thanks for your posts on getting at Outlook from Ruby. Easy working examples that have saved me a fair deal of time. I need to tackle some basic Sharepoint integration next. Hope it's easy too.