Get Email id using attribute ldap

Below is demo program to show to you how to get Email id using attribute 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.
How to get email id using attribute from LDAP server or use below program fetch mail id from ldap server:

package com.ldap;

import java.util.Properties;

import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
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 GetSingleEmailIDFromLDAPUsingAttributes {

	public static void main(String[] args) {
		Properties prop = new Properties();
		prop.put("java.naming.factory.initial",
				"com.sun.jndi.ldap.LdapCtxFactory");
		prop.put("java.naming.provider.url", "ldap://domainname:portnumber");
		prop.put("java.naming.security.principal", " domainname \\username");
		prop.put("java.naming.security.credentials", "password");

		try {
			DirContext ctx = new InitialLdapContext(prop, null);
			SearchControls searchControls = new SearchControls();
			searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
			String attlist[] = { "cn", "mail", "sn", "samaccountname" };
			String ldap_search_context = "ou=Associates,dc= domainname ,dc=companyname,dc=com";
			NamingEnumeration answer = null;
			Attributes matchAttrs = new BasicAttributes(true);
			matchAttrs.put("samaccountname", "userid");
			answer = ctx.search(ldap_search_context, matchAttrs, attlist);
			while (answer.hasMore()) {
				SearchResult sr = (SearchResult) answer.next();
				Attributes attributes = sr.getAttributes();
				System.out.println(attributes.get("mail"));

			}
			ctx.close();

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

}

 

 

Leave a Reply

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