I need to create a Python script which grabs different information about 1500 Outlook Contacts (out of 20000), based on their email. Until now, I managed to do this:
def grab_user_details(email):
first_name, last_name, department, location = '', '', '', ''
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
gal = outlook.Session.GetGlobalAddressList()
entries = gal.AddressEntries
for i in entries:
user = i.GetExchangeUser()
if user is not None:
if user.PrimarySmtpAddress == email:
first_name = email.split("@")[0].split(".")[0].title()
last_name = email.split("@")[0].split(".")[1].title()
department = user.Department
location = user.OfficeLocation
print(email, first_name, last_name, department, location)
break
In the end, the code just iterates through the GAL for that specific email. After finding it, it breaks, and continues searching for the next email. This method is fast for emails starting with A, or at least B... but when you have a GAL with 20000 emails, you can't just wait 2 days for it to finish the whole alphabet.
Is there a faster way of doing this?
Thanks!
Based on @Eugene Astafiev's answer (thank you!), I came up with the following code:
This method is way faster than searching through the GAL.
There's one more thing I need to fix: unfortunately, some users have 2 email address', and .CreateRecipient(email) returns nothing, although outlook can find it. I need to dig into this a little bit more.