Get All Email Id from LDAP

Get All Email Id from LDAP

Below is demo program to show to you how to get all Email All Email Id from 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.

Email All Email Id from LDAP java.

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.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;

public class GetAllEmailIDFromLDAP {
	public GetAllEmailIDFromLDAP()  
	   {  
	     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;
	       Attributes matchAttrs = new BasicAttributes(true);
	       matchAttrs.put("samaccountname","mail");
	       String lettersValue="a;b;c;d;e;f;g;h;i;j;k;l;m;n;o;p;q;r;s;t;u;v;w;x;y;z;";
	       String letters[]=lettersValue.split(";");
	       int i=0;
	       for (String string : letters) {
	        answer = ctx.search(ldap_search_context, "mail="+string+"*",searchControls);
	       while(answer.hasMore())
	       {
	        SearchResult sr = (SearchResult)answer.next();
	        Attributes attributes=sr.getAttributes();
	        Attribute mailID=attributes.get("mail");
	        if (mailID!=null) {
	        System.out.println("Total No: "+i+"  "+mailID.get());
	   }
	        i++;

	       }  
	   }

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

	   }  

	   public static void main(String[] args)  
	   {  
	   GetAllEmailIDFromLDAP ldaptest = new GetAllEmailIDFromLDAP();  
	   } 
}

 

 

Leave a Reply

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