By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,136 Members | 2,135 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,136 IT Pros & Developers. It's quick & easy.

win32com.client (Howto edit Contacts in Outlook)

P: n/a
I am trying to edit Contacts in Outlook. This is so I can transfer numbers
from my address book which is an Excel spreadsheet to my mobile phone. I
came across the following snippet of code which enabled me to the contacts
at least list. I had to root around to discover CdoDefaultFolderContacts
(though it was guessable; how could I enumerate win32com.client.constants?).

I now want to work through the Contacts in Outlook patching in data from my
spreadsheet, and also making new contacts where there is an entry in my
spreadsheet which has not gone into Contacts already.

Where can I find the API? I downloaded OutlookSpy but it is not clear to me
that it can display the structure of the data, nor does it list methods for
objects (a Contact, a Folder of Contacts) that I had hoped.

TIA,

Bill

class Folder (object):
def __init__ (self, folder):
self._folder = folder
def __getattr__ (self, attribute):
return getattr (self._folder, attribute)
def __iter__ (self):
#
# NB You *must* collect a reference to the
# Messages collection here; otherwise GetFirst/Next
# resets every time.
#
messages = self._folder.Messages
message = messages.GetFirst ()
while message:
yield message
message = messages.GetNext ()

if __name__ == '__main__':
import win32com.client
session = win32com.client.gencache.EnsureDispatch ("MAPI.Session")
constants = win32com.client.constants
session.Logon ("Outlook")

#
# CdoDefaultFolderInbox
# CdoDefaultFolderSentItems
# CdoDefaultFolderContacts
#
contact_items = Folder (session.GetDefaultFolder
(constants.CdoDefaultFolderContacts))
for message in contact_items:
print message
sys.exit(1)
print message.Subject
Jul 4 '08 #1
Share this Question
Share on Google+
11 Replies


P: n/a
Bill Davy wrote:
I am trying to edit Contacts in Outlook. This is so I can transfer numbers
from my address book which is an Excel spreadsheet to my mobile phone. I
came across the following snippet of code
--- hey! that looks familiar :)
which enabled me to the contacts
at least list. I had to root around to discover CdoDefaultFolderContacts
(though it was guessable; how could I enumerate win32com.client.constants?).
Well that bit's easy: win32com.client.constants is a small class with
a __dicts__ attribute (note the "s") which is a list of dictionaries, one
per generated library. So you can do something like this:

<code>
import win32com.client

outlook = win32com.client.gencache.EnsureDispatch ("Outlook.Application")
outlook_constants = win32com.client.constants.__dicts__[0]

for k, v in outlook_constants.items ():
print k, "=>", v

</code>
I now want to work through the Contacts in Outlook patching in data from my
spreadsheet, and also making new contacts where there is an entry in my
spreadsheet which has not gone into Contacts already.
OK.
Where can I find the API?
I recommend:

http://msdn.microsoft.com/en-us/library/ms526861.aspx

and

http://www.outlookcode.com/article.aspx?id=20

and

http://www.cdolive.com/cdo10.htm

TJG
Jul 4 '08 #2

P: n/a
"Tim Golden" <ma**@timgolden.me.ukwrote in message
news:ma*************************************@pytho n.org...
Bill Davy wrote:
>I am trying to edit Contacts in Outlook. This is so I can transfer
numbers from my address book which is an Excel spreadsheet to my mobile
phone. I came across the following snippet of code

--- hey! that looks familiar :)
>which enabled me to the contacts at least list. I had to root around to
discover CdoDefaultFolderContacts (though it was guessable; how could I
enumerate win32com.client.constants?).

Well that bit's easy: win32com.client.constants is a small class with
a __dicts__ attribute (note the "s") which is a list of dictionaries, one
per generated library. So you can do something like this:

<code>
import win32com.client

outlook = win32com.client.gencache.EnsureDispatch ("Outlook.Application")
outlook_constants = win32com.client.constants.__dicts__[0]

for k, v in outlook_constants.items ():
print k, "=>", v

</code>
>I now want to work through the Contacts in Outlook patching in data from
my spreadsheet, and also making new contacts where there is an entry in
my spreadsheet which has not gone into Contacts already.

OK.
>Where can I find the API?

I recommend:

http://msdn.microsoft.com/en-us/library/ms526861.aspx

and

http://www.outlookcode.com/article.aspx?id=20

and

http://www.cdolive.com/cdo10.htm

TJG

Brilliant. But I was a bit disappointed by one experiment. In MSDN I found
"Exploring the Outlook Object Model". That suggested:
Outlook | Tools | Macros | VB Editor | View | Object Browser

There I found ContactItems and reckoned I was onto a winner, but found that
a "message" from the ContactFolder might have Subject but it did not have a
FullName. Also, if Python crashed, it left Outlook complaing that someone
was accessing it but had disappeaared so Outlook has to be restarted each
time.

But you have suggested some more things to look at so thanks. I have had a
quick look but have not so far even found "Subject" as a member/property of
a message/contact. I shall keep looking.

Rgds,
Bill
Jul 4 '08 #3

P: n/a
"Bill Davy" <Bi**@SynectixLtd.comwrote in message
news:lP******************************@bt.com...
"Tim Golden" <ma**@timgolden.me.ukwrote in message
news:ma*************************************@pytho n.org...
>Bill Davy wrote:
>>I am trying to edit Contacts in Outlook. This is so I can transfer
numbers from my address book which is an Excel spreadsheet to my mobile
phone. I came across the following snippet of code

--- hey! that looks familiar :)
>>which enabled me to the contacts at least list. I had to root around to
discover CdoDefaultFolderContacts (though it was guessable; how could I
enumerate win32com.client.constants?).

Well that bit's easy: win32com.client.constants is a small class with
a __dicts__ attribute (note the "s") which is a list of dictionaries, one
per generated library. So you can do something like this:

<code>
import win32com.client

outlook = win32com.client.gencache.EnsureDispatch ("Outlook.Application")
outlook_constants = win32com.client.constants.__dicts__[0]

for k, v in outlook_constants.items ():
print k, "=>", v

</code>
>>I now want to work through the Contacts in Outlook patching in data from
my spreadsheet, and also making new contacts where there is an entry in
my spreadsheet which has not gone into Contacts already.

OK.
>>Where can I find the API?

I recommend:

http://msdn.microsoft.com/en-us/library/ms526861.aspx

and

http://www.outlookcode.com/article.aspx?id=20

and

http://www.cdolive.com/cdo10.htm

TJG


Brilliant. But I was a bit disappointed by one experiment. In MSDN I
found "Exploring the Outlook Object Model". That suggested:
Outlook | Tools | Macros | VB Editor | View | Object Browser

There I found ContactItems and reckoned I was onto a winner, but found
that a "message" from the ContactFolder might have Subject but it did not
have a FullName. Also, if Python crashed, it left Outlook complaing that
someone was accessing it but had disappeaared so Outlook has to be
restarted each time.

But you have suggested some more things to look at so thanks. I have had
a quick look but have not so far even found "Subject" as a member/property
of a message/contact. I shall keep looking.

Rgds,
Bill

I kept looking and thought I was saved when I found Receipe 10.16 in the
Python Cookbook but ....

I changed the following:

self.oOutlookApp = Dispatch("Outlook.Application")
#self.oOutlookApp =
gencache.EnsureDispatch("Outlook.Application")

Because gencache failed and I hade run makepy last week (I only get one day
a week to look at this).

Then the following failed because (as I found) olFolderContacts is not in
any of constants' dictionaries.

ofContacts = onMAPI.GetDefaultFolder(constants.olFolderContacts )

So, sadly, I shall have to put this aside for another week and get on with
some work. Any thoughts would be gratefully accepted.

TIA,
Bill
Jul 4 '08 #4

P: n/a
"Bill Davy" <Bi**@SynectixLtd.comwrote:
>
I am trying to edit Contacts in Outlook. This is so I can transfer numbers
from my address book which is an Excel spreadsheet to my mobile phone.
Are you actually running Outlook? Your news posting was made from Outlook
Express, and Outlook Express cannot be controlled by COM (although MAPI
works).
--
Tim Roberts, ti**@probo.com
Providenza & Boekelheide, Inc.
Jul 6 '08 #5

P: n/a
"Tim Roberts" <ti**@probo.comwrote in message
news:h6********************************@4ax.com...
"Bill Davy" <Bi**@SynectixLtd.comwrote:
>>
I am trying to edit Contacts in Outlook. This is so I can transfer
numbers
from my address book which is an Excel spreadsheet to my mobile phone.

Are you actually running Outlook? Your news posting was made from Outlook
Express, and Outlook Express cannot be controlled by COM (although MAPI
works).
--
Tim Roberts, ti**@probo.com
Providenza & Boekelheide, Inc.

I'm not sure OL2003 can read news. I think perhaps some later OL can (added
tot he View menu, perhaps?). So I use OL Express to read news. The OL with
which I wish to communicate is:

Application name Outlook
Version 11.0
Build 8217
Product ID 70141-700-0350904-56905
Language English (United States)
Application Path C:\Program Files\Microsoft Office\OFFICE11\
System Language English (United Kingdom)
Mail Support Not Available
Current folder Inbox
Current item Not Available

Not sure why its says "Mail Support Not Available" as all I use it for is
email (oh, and the calendar).

Hey and ho
Bill
Jul 10 '08 #6

P: n/a
Bill Davy wrote:
I'm not sure OL2003 can read news. I think perhaps some later OL can (added
tot he View menu, perhaps?). So I use OL Express to read news. The OL with
which I wish to communicate is:

Application name Outlook
Version 11.0
Build 8217
Product ID 70141-700-0350904-56905
Language English (United States)
Application Path C:\Program Files\Microsoft Office\OFFICE11\
System Language English (United Kingdom)
Mail Support Not Available
Current folder Inbox
Current item Not Available
Where did you get to with this, Bill? I wasn't sure if no news
was good news or whether you'd gone a different way, or
were still trying things...

TJG
Jul 10 '08 #7

P: n/a
"Tim Golden" <ma**@timgolden.me.ukwrote in message
news:ma**************************************@pyth on.org...
Bill Davy wrote:
>I'm not sure OL2003 can read news. I think perhaps some later OL can
(added tot he View menu, perhaps?). So I use OL Express to read news.
The OL with which I wish to communicate is:

Application name Outlook
Version 11.0
Build 8217
Product ID 70141-700-0350904-56905
Language English (United States)
Application Path C:\Program Files\Microsoft Office\OFFICE11\
System Language English (United Kingdom)
Mail Support Not Available
Current folder Inbox
Current item Not Available

Where did you get to with this, Bill? I wasn't sure if no news
was good news or whether you'd gone a different way, or
were still trying things...

TJG

Hi Tim,
Well, at 5pm last Friday I posted:
"

I kept looking and thought I was saved when I found Receipe 10.16 in the
Python Cookbook but ....

I changed the following:

self.oOutlookApp = Dispatch("Outlook.Application")
#self.oOutlookApp =
gencache.EnsureDispatch("Outlook.Application")

Because gencache failed and I hade run makepy last week (I only get one day
a week to look at this).

Then the following failed because (as I found) olFolderContacts is not in
any of constants' dictionaries.

ofContacts = onMAPI.GetDefaultFolder(constants.olFolderContacts )

So, sadly, I shall have to put this aside for another week and get on with
some work. Any thoughts would be gratefully accepted.

TIA,
Bill
"

and since then have been busy with work, and my other job, and the garden.
Now I am back looking at this (and using WInUSB to talk to a Maxim 3421E etc
etc but that's another story). So any help today will be much appreciated.
Rgds,
Bill
Jul 11 '08 #8

P: n/a
Bill Davy wrote:
and since then have been busy with work, and my other job, and the garden.
Aha! So you're English, are you? Looks like you're in the West Country.
Weather map suggests you're not short of rain over there :)
Now I am back looking at this (and using WInUSB to talk to a Maxim 3421E etc
etc but that's another story). So any help today will be much appreciated.
Rgds,
Can't remember what the particular obstacles were you
were facing, but this runs OK on my setup -
Python 2.5.2 / pywin32 211 / Outlook 2003:

<code>
import os, sys
import win32com.client
constants = win32com.client.constants

def items (contacts):
items = contacts.Items
item = items.GetFirst ()
while item:
yield item
item = items.GetNext ()

#
# Add whatever fields you like from:
# http://msdn.microsoft.com/en-us/libr...ffice.11).aspx
#
FIELDS = ['FullName', 'CompanyName', 'Email1Address']

outlook = win32com.client.gencache.EnsureDispatch ("Outlook.Application")
ns = outlook.GetNamespace ("MAPI")
for contact in items (ns.GetDefaultFolder (constants.olFolderContacts)):
if contact.Class == constants.olContact:
print contact
for field in FIELDS:
print " ", field, "=>", getattr (contact, field, "<Unknown>")

</code>

Hope that helps.
TJG
Jul 11 '08 #9

P: n/a
"Tim Golden" <ma**@timgolden.me.ukwrote in message
news:ma**************************************@pyth on.org...
Bill Davy wrote:
>and since then have been busy with work, and my other job, and the
garden.

Aha! So you're English, are you? Looks like you're in the West Country.
Weather map suggests you're not short of rain over there :)
>Now I am back looking at this (and using WInUSB to talk to a Maxim 3421E
etc etc but that's another story). So any help today will be much
appreciated.
Rgds,

Can't remember what the particular obstacles were you
were facing, but this runs OK on my setup -
Python 2.5.2 / pywin32 211 / Outlook 2003:

<code>
import os, sys
import win32com.client
constants = win32com.client.constants

def items (contacts):
items = contacts.Items
item = items.GetFirst ()
while item:
yield item
item = items.GetNext ()

#
# Add whatever fields you like from:
# http://msdn.microsoft.com/en-us/libr...ffice.11).aspx
#
FIELDS = ['FullName', 'CompanyName', 'Email1Address']

outlook = win32com.client.gencache.EnsureDispatch ("Outlook.Application")
ns = outlook.GetNamespace ("MAPI")
for contact in items (ns.GetDefaultFolder (constants.olFolderContacts)):
if contact.Class == constants.olContact:
print contact
for field in FIELDS:
print " ", field, "=>", getattr (contact, field, "<Unknown>")

</code>

Hope that helps.
TJG

jUST IN CASE,. i CUT'NPASTED THE PROGRAM:

import os, sys
import win32com.client
constants = win32com.client.constants

def items (contacts):
items = contacts.Items
item = items.GetFirst ()
while item:
yield item
item = items.GetNext ()

#
# Add whatever fields you like from:
# http://msdn.microsoft.com/en-us/libr...ffice.11).aspx
#
FIELDS = ['FullName', 'CompanyName', 'Email1Address']

outlook = win32com.client.gencache.EnsureDispatch ("Outlook.Application")
ns = outlook.GetNamespace ("MAPI")
for contact in items (ns.GetDefaultFolder (constants.olFolderContacts)):
if contact.Class == constants.olContact:
print contact
for field in FIELDS:
print " ", field, "=>", getattr (contact, field, "<Unknown>")

---------------------------------------------------------------------------------------------------
And then I ran it:

Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)]
on win32
Type "copyright", "credits" or "license()" for more information.

************************************************** **************
Personal firewall software may warn about the connection IDLE
makes to its subprocess using this computer's internal loopback
interface. This connection is not visible on any external
interface and no data is sent to or received from the Internet.
************************************************** **************

IDLE 1.2.2
>>================================ RESTART
================================
Traceback (most recent call last):
File "H:/Personal/OutlookIF1/t2.py", line 18, in <module>
outlook = win32com.client.gencache.EnsureDispatch
("Outlook.Application")
File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line
536, in EnsureDispatch
mod = EnsureModule(tla[0], tla[1], tla[3], tla[4],
bForDemand=bForDemand)
File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line
393, in EnsureModule
module = GetModuleForTypelib(typelibCLSID, lcid, major, minor)
File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line
262, in GetModuleForTypelib
AddModuleToCache(typelibCLSID, lcid, major, minor)
File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line
554, in AddModuleToCache
dict = mod.CLSIDToClassMap
AttributeError: 'module' object has no attribute 'CLSIDToClassMap'
>>>
-------------------------------------------------------------------------------------------------

Outlook is running fine.

This is how the fucntion where the failure occurs begins:

def AddModuleToCache(typelibclsid, lcid, major, minor, verbose = 1,
bFlushNow = not is_readonly):
"""Add a newly generated file to the cache dictionary.
"""
fname = GetGeneratedFileName(typelibclsid, lcid, major, minor)
mod = _GetModule(fname)
# if mod._in_gencache_ is already true, then we are reloading this
# module - this doesn't mean anything special though!
mod._in_gencache_ = 1
dict = mod.CLSIDToClassMap
info = str(typelibclsid), lcid, major, minor
for clsid, cls in dict.items():
clsidToTypelib[clsid] = info

-----------------------------------------------------------------------------------------------

Yes, we have suffiicient rain but the gaden needed it. I am about to become
the proud tenant of half an allotment. Still, this time last year we had
floods.

TIA,
Bill
Jul 11 '08 #10

P: n/a
Bill Davy wrote:
Traceback (most recent call last):
File "H:/Personal/OutlookIF1/t2.py", line 18, in <module>
outlook = win32com.client.gencache.EnsureDispatch
("Outlook.Application")
File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line
536, in EnsureDispatch
mod = EnsureModule(tla[0], tla[1], tla[3], tla[4],
bForDemand=bForDemand)
File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line
393, in EnsureModule
module = GetModuleForTypelib(typelibCLSID, lcid, major, minor)
File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line
262, in GetModuleForTypelib
AddModuleToCache(typelibCLSID, lcid, major, minor)
File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line
554, in AddModuleToCache
dict = mod.CLSIDToClassMap
AttributeError: 'module' object has no attribute 'CLSIDToClassMap'

Just in case, could you delete the contents of your gen_py
directory (probably in %TEMP%\gen_py)

TJG
Jul 11 '08 #11

P: n/a
"Tim Golden" <ma**@timgolden.me.ukwrote in message
news:ma**************************************@pyth on.org...
Bill Davy wrote:
>Traceback (most recent call last):
File "H:/Personal/OutlookIF1/t2.py", line 18, in <module>
outlook = win32com.client.gencache.EnsureDispatch
("Outlook.Application")
File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line
536, in EnsureDispatch
mod = EnsureModule(tla[0], tla[1], tla[3], tla[4],
bForDemand=bForDemand)
File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line
393, in EnsureModule
module = GetModuleForTypelib(typelibCLSID, lcid, major, minor)
File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line
262, in GetModuleForTypelib
AddModuleToCache(typelibCLSID, lcid, major, minor)
File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line
554, in AddModuleToCache
dict = mod.CLSIDToClassMap
AttributeError: 'module' object has no attribute 'CLSIDToClassMap'


Just in case, could you delete the contents of your gen_py
directory (probably in %TEMP%\gen_py)

TJG


OK, Put the following ahead with the following results.

TempDir = os.getenv("TEMP");
WorkDir = TempDir + '\\gen_py'
print WorkDir
try:
os.rmdir(WorkDir);
except WindowsError, detail:
print "Ignoring Windows error: ", detail

....

Result:
C:\DOCUME~1\Bill\LOCALS~1\Temp\gen_py
Ignoring Windows error: [Error 2] The system cannot find the file
specified: 'C:\\DOCUME~1\\Bill\\LOCALS~1\\Temp\\gen_py'

Traceback (most recent call last):
File "H:\Personal\OutlookIF1\t2.py", line 26, in <module>
outlook = win32com.client.gencache.EnsureDispatch
("Outlook.Application")
File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line
536, in EnsureDispatch
mod = EnsureModule(tla[0], tla[1], tla[3], tla[4],
bForDemand=bForDemand)
File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line
393, in EnsureModule
module = GetModuleForTypelib(typelibCLSID, lcid, major, minor)
File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line
262, in GetModuleForTypelib
AddModuleToCache(typelibCLSID, lcid, major, minor)
File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line
554, in AddModuleToCache
dict = mod.CLSIDToClassMap
AttributeError: 'module' object has no attribute 'CLSIDToClassMap'
>>>
So, although that directory did exist, it does not now (even after the
program has run).

Any other ideas?

But many thnaks,
Bill
Jul 12 '08 #12

This discussion thread is closed

Replies have been disabled for this discussion.