using ADODB and python to retreive an email address

Ok, here is the code sample I promised. This was the best way I could come up with to get the Exchange email address of an Active Directory user when all I knew was their SAM account name. The following Python code worked for me running on Win32:

import win32com.client
def getEmail(user):
    #create an ADODB connection to get the email address for the logged in user
    conn = win32com.client.Dispatch(’ADODB.Connection’)
    conn.Provider = ‘ADsDSOObject’
    conn.Open()
    #query for email address
    query = ‘<ldap ://yourdomain.com>;(sAMAccountName=%s);mail;subtree’ % user
    rs = conn.Execute(query)
    email = str(rs[0].Fields(0).Value) #here is where the email address is located in the record set
    rs[0].Close()
    conn.Close()
    return email
exch_email= getEmail(’jpublic’)

There you have it. It might not be the prettiest thing in the world, but it works for me. Feel free to comment if you have any thoughts.

Christian

Leave a Reply