通过python检索outlook联系人

时间:2012-07-18 09:43:20

标签: python outlook

我正在尝试使用OutlookPython中获取联系人。 代码是:

import win32com.client
import pywintypes

o = win32com.client.Dispatch("Outlook.Application")
ns = o.GetNamespace("MAPI")
profile = ns.Folders.Item("Outlook")
contacts = profile.Folders.Item("Contacts")

但它给出的错误是这样的:

Traceback (most recent call last):
  File "my_pro.py", line 7, in <module>
    profile = ns.Folders.Item("Outlook")
  File "C:\DOCUME~1\Manoj\LOCALS~1\Temp\gen_py\2.7\00062FFF-0000-0000-C000-00000
0000046x0x9x3\_Folders.py", line 70, in Item
    ret = self._oleobj_.InvokeTypes(81, LCID, 1, (9, 0), ((12, 1),),Index
pywintypes.com_error: (-2147352567, 'Exception occurred.', (4096, u'Microsoft Of
fice Outlook', u'The operation failed. An object could not be found.', None, 0,
-2147221233), None)

我无法理解为什么它的抛出错误,因为我有一个名为Outlook的配置文件 感谢

4 个答案:

答案 0 :(得分:8)

这里有一个python配方来读取outlook中的联系人。 希望它会有用。他正在使用GetDefaultFolder而不是Folders.Item函数。

http://code.activestate.com/recipes/173216-import-outlook-contacts-using-win32com/

答案 1 :(得分:2)

您可能没有名为“Outlook”的个人资料(除非您创建了一个)

通常,“个人资料名称”是您的“收件箱”所在的顶级文件夹的名称。如“个人文件夹”

答案 2 :(得分:0)

  • 此选项适用于从 Outlook.pst 文件(而非 Exchange 服务器)中提取联系人。
    • 请参阅此 answer 以从 Exchange 服务器上的全局地址列表中提取联系人。
  • 这需要在 Windows 上安装 Outlook,但未运行。
    • 使用 python 3.8、Windows 10、Outlook Office 365 进行测试
  • 创建 contacts_items 对象后,使用适当的 Property 提取所需信息。
  • 我注意到 outlook.Application.Quit() 并未关闭 Outlook,因此可能需要在任务管理器中将其关闭。
import win32com.client

# create outlook object
outlook = win32com.client.Dispatch("Outlook.Application")
ns = outlook.GetNamespace("MAPI")

# create an object for the contacts in the default folder
contacts_items = ns.GetDefaultFolder(10).Items

# print name and email address
for c in contacts_items:
    print(f'{c.FullName}: {c.Email1Address}')

# create a dict of contacts
contacts = {c.FullName: c.Email1Address for c in contacts_items}

# close the application
outlook.Application.Quit()

MSOutlook Class

import win32com.client


DEBUG = 0

class MSOutlook:
    def __init__(self):
        self.outlookFound = 0
        try:
            self.oOutlookApp = \
                win32com.client.gencache.EnsureDispatch("Outlook.Application")
            self.outlookFound = 1
        except:
            print("MSOutlook: unable to load Outlook")
        
        self.records = []


    def loadContacts(self, keys=None):
        if not self.outlookFound:
            return

        # this should use more try/except blocks or nested blocks
        onMAPI = self.oOutlookApp.GetNamespace("MAPI")
        ofContacts = \
            onMAPI.GetDefaultFolder(win32com.client.constants.olFolderContacts)

        if DEBUG:
            print(f"number of contacts: {len(ofContacts.Items)}")

        for oc in range(len(ofContacts.Items)):
            contact = ofContacts.Items.Item(oc + 1)
            if contact.Class == win32com.client.constants.olContact:
                if keys is None:
                    # if we were't give a set of keys to use
                    # then build up a list of keys that we will be
                    # able to process
                    # I didn't include fields of type time, though
                    # those could probably be interpreted
                    keys = []
                    for key in contact._prop_map_get_:
                        if isinstance(getattr(contact, key), (int, str, unicode)):
                            keys.append(key)
                    if DEBUG:
                        keys.sort()
                        print("Fields\n======================================")
                        for key in keys:
                            print(key)
                record = {}
                for key in keys:
                    record[key] = getattr(contact, key)
                if DEBUG:
                    print(oc, record['FullName'])
                self.records.append(record)

类使用

if DEBUG:
    print("attempting to load Outlook")
oOutlook = MSOutlook()
# delayed check for Outlook on win32 box
if not oOutlook.outlookFound:
    print("Outlook not found")
    sys.exit(1)

fields = ['FullName',
            'CompanyName', 
            'MailingAddressStreet',
            'MailingAddressCity', 
            'MailingAddressState', 
            'MailingAddressPostalCode',
            'HomeTelephoneNumber', 
            'BusinessTelephoneNumber', 
            'MobileTelephoneNumber',
            'Email1Address',
            'Body'
            ]

if DEBUG:
#     import time
    print("loading records...")
    startTime = time.time()
# you can either get all of the data fields
# or just a specific set of fields which is much faster
#oOutlook.loadContacts()
oOutlook.loadContacts(fields)
if DEBUG:
    print(f"loading took {time.time() - startTime} seconds")

print(f"Number of contacts: {len(oOutlook.records)}")
    
for i in range(len(oOutlook.records)):
    print(f"Contact: {oOutlook.records[i]['FullName']}")
    print(f"Body:\n{oOutlook.records[i]['Body']}")

答案 3 :(得分:0)

  • 此选项适用于在 Outlook 连接到 Exchange 服务器时提取联系人。
  • 我设法找到/修改了一个可行的解决方案。它将 Outlook 中所有联系人的电子邮件地址和全名保存为列表:
import win32com.client

# Outlook stuff
outApp = win32com.client.gencache.EnsureDispatch("Outlook.Application")
outGAL = outApp.Session.GetGlobalAddressList()
entries = outGAL.AddressEntries

# Empty list to store contact info
data_set = list()

# Iterates through your contact book and extracts/appends them to a list
for entry in entries:
    if entry.Type == "EX":
        user = entry.GetExchangeUser()
        if user is not None:
            if len(user.FirstName) > 0 and len(user.LastName) > 0:
                row = list()
                row.append(user.FirstName)
                row.append(user.LastName)
                row.append(user.PrimarySmtpAddress)
                """print("First Name: " + user.FirstName)
                print("Last Name: " + user.LastName)
                print("Email: " + user.PrimarySmtpAddress)"""
                data_set.append(row)

# Prints list
print(data_set)

原代码: https://www.excelcise.org/getting-information-from-outlook-global-address-list-gal-with-python/