We've looked at sending email, working with calendar appointments, and creating and managing tasks with Outlook. Next we'll take a look at how to create new contacts and read contacts data from Outlook.
You know by now how this starts out: we'll use the win32ole library to create a new instance (or connect to a currently running instance) of the Outlook application object:
require 'win32ole'
outlook = WIN32OLE.new('Outlook.Application')
Next we'll get the MAPI namespace:
mapi = outlook.GetNameSpace('MAPI')
Creating a New Contact
To create a new contact, call the Outlook Application object's CreateItem method, passing it the number 2, which represents a Contact Item. This returns a new Contact object:
contact = outlook.CreateItem(2)
Then set values for various properties of the new Contact object:
contact.FullName = 'Stan Musial'
contact.CompanyName = 'St. Louis Cardinals'
contact.JobTitle = 'Hitter'
contact.BusinessTelephoneNumber = '(314)555-1234'
contact.Email1Address = 'stan_the_man@stlcardinals.com'
What properties are available to set? Dozens. To see a list, you could call contact.ole_methods, Google for it (Outlook Contact Properties), or use an OLE object browser.
When you've completed setting property values, call the Contact object's Save method:
contact.Save
Getting Existing Contacts Data
To obtain a collection of Contacts, call the MAPI object's GetDefaultFolder method, passing it the integer 10, which represents the Contacts folder. Then call the Items method on this object:
contacts = mapi.GetDefaultFolder(10).Items
You can now iterate over this collection of Contact objects, calling the methods/properties to get the data you need:
contacts.each do |contact|
puts contact.FullName
puts contact.Email1Address
puts contact.BusinessTelephoneNumber
end
For further information, check out these Microsoft TechNet articles:
Creating a New Contact in Microsoft Outlook
Exporting Contact Information
As always, feel free to post a comment here or send me email with questions, comments, or suggestions.
Thanks for stopping by!
1 comment:
Hi there! Thanks for the great post!
BTW, do you think it is possible to avoid a security message box like "A program is trying top access a-mail addresses you've stored in outlook" when access some of contact details (say, Email1Address).
Post a Comment