3

我正在尝试让联系人停止Outlook使用Python. 代码是:

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

3 回答 3

2

您可能没有名为“Outlook”的配置文件(除非您创建了一个)

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

于 2012-09-30T01:25:18.533 回答
1
  • 此选项适用于从Outlook.pst文件中提取联系人,而不是从 Exchange 服务器中提取。
    • 请参阅此答案以从 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']}")
于 2021-01-19T21:58:45.923 回答
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/

于 2021-01-19T23:16:16.867 回答