Get single email id ldap

Below is demo program to show to you how to get single email id ldap server. Please use this program

and replace your LDAP domain name and port number and it also need valid user id and password to access the record from LDAP server.

Get single email id ldap server or how to Get single email id ldap:

package com.ldap;

import java.util.Properties;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;

public class GetSingleEmailIDFromLDAP {

	public static void main(String[] args) {
		Properties prop = new Properties();
		prop.put(Context.INITIAL_CONTEXT_FACTORY,
				"com.sun.jndi.ldap.LdapCtxFactory");
		prop.put(Context.PROVIDER_URL, "ldap://domainname:portnumber");
		prop.put(Context.SECURITY_PRINCIPAL, " domainname \\username");
		prop.put(Context.SECURITY_CREDENTIALS, "password");

		try {

			DirContext ctx = new InitialLdapContext(prop, null);
			SearchControls searchControls = new SearchControls();
			searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
			String ldap_search_context = "ou=Associates,dc= domainname ,dc=companyname,dc=com";
			NamingEnumeration answer = null;
			answer = ctx.search(ldap_search_context, "samaccountname=userid",
					searchControls);
			while (answer.hasMore()) {
				SearchResult sr = (SearchResult) answer.next();
				Attributes attributes = sr.getAttributes();
				Attribute mailID = attributes.get("mail");
				if (mailID != null) {
					System.out.println(mailID.get());
				}

			}
			ctx.close();
		} catch (NamingException ex) {
			ex.printStackTrace();
		}
	}

}

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *