473,406 Members | 2,312 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

win32com.client (Howto edit Contacts in Outlook)

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
11 7608
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
"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
"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
"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
"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
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
"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
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
"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
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
"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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Justin Stockton | last post by:
I recently upgraded from ActivePython 2.2.2 to ActivePython 2.3.2 and I'm running into an issue importing the win32com.client module. Before installing the new version, I made sure to properly...
0
by: neblackcat | last post by:
This is a heads-up on a possible memory corruption type of bug in recent and present versions of Python/win32com. I dont know if its general, or specific to using win32com.client to access CDO as...
2
by: Fritz Switzer | last post by:
Can anyone provide a small snippet in C# that pulls out the Contacts in Outlook XP. I've seen a couple of examples in C++ and VB in previous newsgroup posts, but either the originals didn't work...
2
by: Kurt Häusler | last post by:
Hi. I have am using c# and the outlook object model to access the outlook address book, but once you have more than a 100 or so contacts in the folder it takes far too long to iterate through...
7
by: Chris Thunell | last post by:
I'm trying to loop through an exchange public folder contact list, get some information out of each item, and then put it into a vb.net datatable. I run though the code and all works fine until i...
1
by: charliej2001 | last post by:
Hi all My access database has import/export capabiltiy of contact details between outlook. The database is getting big now (1000+ contacts) and so are the outlook address books that have the...
1
by: dcd | last post by:
Hi all I'm using trying to get my app to read in all contacts in the contact folder of Outlook. I'm using the Outlook Security manager to stop the pop up warnings. Outlook version is...
1
by: Phil Stanton | last post by:
I have a Yacht Club Db with names addresse phone nos, emails etc. I want to export them to Outlook. No problem in getting them into the contact folder. My problem is I have a folder within the...
3
by: Volkan Senguel | last post by:
Hi Is there a easy way to get the contacts (names and phonenumbers) from outlook without the message that someone is accessing outlook and how long the access can take? i have not found any...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.