Automating Microsoft Outlook

For Outlook automation it is nesseccary to use the makepy utility. You do this either from the tools menu of the Pythonwin-Editor (installed with Pywin32 or ActivePython) or you call the file c:\python23\Lib\site-packages\win32com\client\makepy.py. You then have to select the Outlook Object Library (“Microsoft Outlook 10.0 Object Library” for Office 10.0 or known as Office XP).

After that Python generates cachefiles into the directory c:\python23\Lib\site-packages\win32com\gen_py or c:\temp\gen_py to tell Python more about the Outlook object library.

Here is a well known example which dumps all adressbook entries from your default adressbook:

import codecs, win32com.client
# This example dumps the items in the default address book
# needed for converting Unicode->Ansi (in local system codepage)
DecodeUnicodeString = lambda x: codecs.latin_1_encode(x)[0]
def DumpDefaultAddressBook():
    # Create instance of Outlook
    o = win32com.client.Dispatch("Outlook.Application")
    mapi = o.GetNamespace("MAPI")
    folder = mapi.GetDefaultFolder(win32com.client.constants.olFolderContacts)
    print "The default address book contains",folder.Items.Count,"items"
    # see Outlook object model for more available properties on ContactItem objects
    attributes = [ 'FullName', 'Email1Address']    
    for i in range(1,folder.Items.Count+1):
        print "~~~ Entry %d ~~~" % i
        item = folder.Items[i]
        for attribute in attributes:
            print attribute, eval('item.%s' % attribute)
    o = None
DumpDefaultAddressBook()

Leave a Reply

Your email address will not be published. Required fields are marked *