![](/img/trans.png)
[英]Sudden error when retrieving emails from Outlook using Python and win32com
[英]Retrieving outlook Contacts via python win32com
我正在尝试使用Python
从Outlook
中获取联系人。 代码是:
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
的配置文件
这里有一个python食谱,可以从Outlook中读取联系人。 希望它会有用。 他正在使用GetDefaultFolder而不是Folders.Item函数。
http://code.activestate.com/recipes/173216-import-outlook-contacts-using-win32com/
您可能没有名为“Outlook”的配置文件(除非您创建了一个)
通常“个人资料名称”是顶级文件夹的名称,即您的“收件箱”所在的文件夹。如“个人文件夹”
Outlook.pst
文件而不是 Exchange 服务器中提取联系人。
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']}")
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/
如果您使用 python 3.9 及更高版本并且您只对 email 地址感兴趣,那么以下就足够了。
import win32com.client
outlook = win32com.client.gencache.EnsureDispatch("Outlook.Application")
addresses = outlook.Session.GetGlobalAddressList().AddressEntries
mails = [
user.PrimarySmtpAddress for x in addresses
if (user := x.GetExchangeUser()) is not None
]
print(mails)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.