I have defined four custom user properties and i can not access to the in order to get their data, custom properties are present in outlook appointment but i can get to them :
My c# code below :
Outlook.ItemProperties itemProp = appointmentItem.ItemProperties;
foreach (Outlook.ItemProperty userprop in itemProp)
{
if (userprop.IsUserProperty)
{
MessageBox.Show(userprop.Name + "\t" + userprop.Value);
}
}
I have used an api(JWebServices) that creates appointment event into Outlook(2007 my version), in my code below i have created some CustomProperties, called in C# Addin Outlook UserPropertie.
I still can get the value of custom users properties that i have defined from the java side
PropertyName myRdvTypePropertyName = new PropertyName("RdvType", StandardPropertySet.PUBLIC_STRINGS);
ExtendedProperty myRdvTypeExtendedProperty = new ExtendedProperty(myRdvTypePropertyName, event.getTyperdv());
appointment.getExtendedProperties().add(myRdvTypeExtendedProperty);
PropertyName myRdvEmplacementPropertyName = new PropertyName("RdvEmplacement", StandardPropertySet.PUBLIC_STRINGS);
ExtendedProperty myRdvEmplacementExtendedProperty = new ExtendedProperty(myRdvEmplacementPropertyName, event.getLieu());
appointment.getExtendedProperties().add(myRdvEmplacementExtendedProperty);
PropertyName myRdvAdressePropertyName = new PropertyName("RdvAdresse", StandardPropertySet.PUBLIC_STRINGS);
ExtendedProperty myRdvAdresseExtendedProperty = new ExtendedProperty(myRdvAdressePropertyName, event.getEvent_location());
appointment.getExtendedProperties().add(myRdvAdresseExtendedProperty);
To be sure the custom user properties are created, i use Outlook SPY
the screenshot below:
the code below in the FormRegionShowing :
if (appointmentItem.UserProperties["RdvType"] != null)
{
this.TypeRdvComboBox.SelectedItem = appointmentItem.UserProperties["RdvType"].Value;
}
if (appointmentItem.UserProperties["RdvEmplacement"] != null)
{
this.emplacementRdvComboBox.SelectedItem = appointmentItem.UserProperties["RdvEmplacement"].Value;
}
if (appointmentItem.UserProperties["RdvAdresse"] != null)
{
this.adresseTextBox.Text = (string)appointmentItem.UserProperties["RdvAdresse"].Value;
}
Thanks for the inspiration, this works:
Outlook.MailItem mItem = (Outlook.MailItem)item;
string udpName = "";
string udpValueString = "";
Debug.Print(" mItem.UserProperties.Count: " + mItem.UserProperties.Count);
for (int i = 1; i <= mItem.UserProperties.Count; i++) {
udpName = mItem.UserProperties[i].Name;
var udpValue = mItem.UserProperties[i].Value;
udpValueString = udpValue.ToString();
Debug.Print(i + ": " + udpName + ": " + udpValueString);
}
Try using the UserProperties property and UserProperties class instead. Here is what MSDN states:
If you use UserProperties.Find to look for a custom property and the call succeeds, it will return a UserProperty object. If it fails, it will return Null. If you use UserProperties.Find to look for a built-in property, specify False for the Custom parameter. If the call succeeds, it will return the property as a UserProperty object. If the call fails, it will return Null. If you specify True for Custom, the call will not find the built-in property and will return Null.
using System.Runtime.InteropServices;
// ...
private void ShowUserProperties(Outlook.MailItem mail)
{
Outlook.UserProperties mailUserProperties = null;
Outlook.UserProperty mailUserProperty = null;
StringBuilder builder = new StringBuilder();
mailUserProperties = mail.UserProperties;
try
{
for (int i = 1; i < = mailUserProperties.Count; i++)
{
mailUserProperty = mailUserProperties[i];
if (mailUserProperty != null)
{
builder.AppendFormat("Name: {0} \tValue: {1} \n\r",
mailUserProperty.Name, mailUserProperty.Value);
Marshal.ReleaseComObject(mailUserProperty);
mailUserProperty = null;
}
}
if (builder.Length > 0)
{
System.Windows.Forms.MessageBox.Show(builder.ToString(),
"The UserProperties collection");
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
finally
{
if (mailUserProperties != null)
Marshal.ReleaseComObject(mailUserProperties);
}
}
Read more about that in the How To: Get Outlook e-mail item’s custom properties – C# and VB.NET samples article.
Related
I want to remove all attachments form a mail in outlook. Don't know, what I'm doing wrong. The code does not cause an exception, but the attachments are still available after removing. This is my code:
This gives me an outlook.application object if it is running or is running outlook, if it's not running:
public static OL.Application GetOutlook(out bool StillRunning)
{
OL.Application OLApp = null;
if (System.Diagnostics.Process.GetProcessesByName("OUTLOOK").Count() > 0)
{
StillRunning = true;
return System.Runtime.InteropServices.Marshal.GetActiveObject("Outlook.Application") as Microsoft.Office.Interop.Outlook.Application;
}
else
{
StillRunning = false;
OLApp = new OL.Application();
OL.NameSpace nameSpace = OLApp.GetNamespace("MAPI");
nameSpace.Logon("", "", System.Reflection.Missing.Value, System.Reflection.Missing.Value);
nameSpace = null;
return OLApp;
}
}
This function returns a mail by its EntryID:
public static OL.MailItem GetMailByEntryId(OL.Application OlApp, string MailItemEntryID)
{
OL.NameSpace olNS = null;
object obj = null;
olNS = OlApp.GetNamespace("MAPI");
if (olNS == null) { throw new System.Exception("ERROR: Unable to get Namespace 'MAPI' in Outlook.Application object!"); }
OL.MailItem MI = null;
obj = olNS.GetItemFromID(MailItemEntryID);
if (obj != null && obj is OL.MailItem) { MI = obj as OL.MailItem; }
if (MI == null) { throw new System.Exception("ERROR: Unable to get mail item by ID " + System.Environment.NewLine + MailItemEntryID); }
return MI;
}
Here, I try to remove the attachments of the mail:
public static void RemoveAttachments(string EntryID)
{
bool StillRunning = false;
OL.Application OLApp = GetOutlook(out StillRunning);
OL.MailItem MI = GetMailByEntryId(OLApp, EntryID);
for(int i = 0; i < MI.Attachments.Count; i++) { MI.Attachments.Remove(i); } //Methode Delete() not available...
MI.Save();
if (!StillRunning) { OLApp.Quit(); OLApp = null; System.GC.Collect(); KillOutlook(); }
}
Thank you all for your help...
All collections in OOM (including MailItem.Attachments) are 1 based, not 0. You are also modifying the collection while looping - use a down loop:
Attachments attachments = MI.Attachments;
for(int i = attachments.Count; i >= 1; i--) { Attachments.Remove(i); }
Ahh, got it - You can make it work that way:
foreach(OL.Attachment Att in MI.Attachments){Att.Delete();}
I'm trying to search my inbox and all subfolders for a given string in the subject line. I found the following code online(https://www.add-in-express.com/creating-addins-blog/2012/05/31/outlook-search-csharp-vbnet/), but it returns zero results which is not the expected result.
I looked at the filter under view settings in outlook for a given search term that returns results in the outlook explorer and got this query: "http://schemas.microsoft.com/mapi/proptag/0x0037001f" LIKE '%Ticket%'
When I plug that in to the below code I likewise get zero results.
When I use LINQ to query those folders(LINQ is too slow to be a real solution here) I can get results so I'm guessing I'm making a syntactical error with advancedsearch. It is hard to find examples of usage on the web. I will appreciate anyone that can help me.
private Search RunAdvancedSearch(Outlook._Application OutlookApp, string wordInSubject)
{
string advancedSearchTag = "New Search";
string scope = "Inbox";
string filter = "\"urn:schemas:mailheader:subject\" LIKE '%"+ wordInSubject +"%'";
Outlook.Search advancedSearch = null;
Outlook.MAPIFolder folderInbox = null;
Outlook.MAPIFolder folderSentMail = null;
Outlook.NameSpace ns = null;
try
{
ns = OutlookApp.GetNamespace("MAPI");
folderInbox = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
folderSentMail = ns.GetDefaultFolder(
Outlook.OlDefaultFolders.olFolderSentMail);
scope = "\'" + folderInbox.FolderPath +
"\',\'" + folderSentMail.FolderPath + "\'";
advancedSearch = OutlookApp.AdvancedSearch(
scope, filter, true, advancedSearchTag);
System.Diagnostics.Debug.WriteLine(advancedSearch.Results.Count);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "An exception is thrown!");
}
finally
{
if (advancedSearch != null) Marshal.ReleaseComObject(advancedSearch);
if (folderSentMail != null) Marshal.ReleaseComObject(folderSentMail);
if (folderInbox != null) Marshal.ReleaseComObject(folderInbox);
if (ns != null) Marshal.ReleaseComObject(ns);
}
return advancedSearch;
}
I was not waiting long enough for the results. When AdvancedSearch(which runs in a separate thread) is finished it fires off an event called AdvancedSearchComplete. I had to tell the code to handle the event in order to wait for the search to complete.
In RunAdvancedSearch I do this in the Try with this:
Application.AdvancedSearchComplete += Application_AdvancedSearchComplete;
Here is the whole thing.
string advancedSearchTag = "MY FOOFOO Search";
//SEARCH Function
Search RunAdvancedSearch(Outlook.Application Application, string wordInSubject)
{
string scope = "Inbox";
string filter = "urn:schemas:mailheader:subject LIKE \'%" + wordInSubject + "%\'";
Outlook.Search advancedSearch = null;
Outlook.MAPIFolder folderInbox = null;
Outlook.MAPIFolder folderSentMail = null;
Outlook.NameSpace ns = null;
try
{
ns = Application.GetNamespace("MAPI");
folderInbox = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
folderSentMail = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderSentMail);
scope = "\'" + folderInbox.FolderPath + "\',\'" +
folderSentMail.FolderPath + "\'";
advancedSearch = Application.AdvancedSearch(
scope, filter, true, advancedSearchTag);
Application.AdvancedSearchComplete += Application_AdvancedSearchComplete;
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "An eexception is thrown");
}
finally
{
if (advancedSearch != null) Marshal.ReleaseComObject(advancedSearch);
if (folderSentMail != null) Marshal.ReleaseComObject(folderSentMail);
if (folderInbox != null) Marshal.ReleaseComObject(folderInbox);
if (ns != null) Marshal.ReleaseComObject(ns);
}
return advancedSearch;
}
//Handle AdvancedSearchComplete event
void Application_AdvancedSearchComplete(Outlook.Search SearchObject)
{
Outlook.Results advancedSearchResults = null;
Outlook.MailItem resultItem = null;
System.Text.StringBuilder strBuilder = null;
try
{
if (SearchObject.Tag == advancedSearchTag)
{
advancedSearchResults = SearchObject.Results;
System.Diagnostics.Debug.WriteLine("Count: " + advancedSearchResults.Count);
if (advancedSearchResults.Count > 0)
{
strBuilder = new System.Text.StringBuilder();
strBuilder.AppendLine("Number of items found: " +
advancedSearchResults.Count.ToString());
foreach (MailItem item in advancedSearchResults)
{
System.Diagnostics.Debug.WriteLine(item.Subject);
}
for (int i = 1; i <= advancedSearchResults.Count; i++)
{
resultItem = advancedSearchResults[i] as Outlook.MailItem;
if (resultItem != null)
{
strBuilder.Append("#" + i.ToString());
strBuilder.Append(" Subject: " + resultItem.Subject);
strBuilder.Append(" \t To: " + resultItem.To);
strBuilder.AppendLine(" \t Date: " +
resultItem.SentOn.ToString());
Marshal.ReleaseComObject(resultItem);
}
}
if (strBuilder.Length > 0)
System.Diagnostics.Debug.WriteLine(strBuilder.ToString());
else
System.Diagnostics.Debug.WriteLine(
"There are no Mail items found.");
}
else
{
System.Diagnostics.Debug.WriteLine("There are no items found.");
}
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "An exception is occured");
}
finally
{
if (resultItem != null) Marshal.ReleaseComObject(resultItem);
if (advancedSearchResults != null)
Marshal.ReleaseComObject(advancedSearchResults);
}
}
private void btnOutlookSrch_Click(object sender, EventArgs e)
{
Outlook.Application OLook = new Outlook.Application();
RunAdvancedSearch(OLook, "Hello?");
}
Your filter is working good, use Application:
private Search RunAdvancedSearch(Outlook.Application OutlookApp, string wordInSubject)
https://msdn.microsoft.com/en-us/library/office/microsoft.office.interop.outlook.application.aspx
Read about using _Application and Application in msdn "Remarks". There is very well written.
I am developing an outlook add-in using add-in express. When I get a outbox mail item, I can see my email address under "mailItem.SenderEmailAddress" as in x500 format. Is there a way to convert it as a SMTP email address.
Here is my code :
Outlook.Explorer expl = null;
Outlook.Selection selection = null;
Outlook.MailItem mailItem = null;
Outlook.Recipient recipient = null;
string recipientsEmail = "";
try
{
expl = Globals.ObjOutlook.ActiveExplorer() as Outlook.Explorer; ;
if (expl != null)
{
selection = expl.Selection;
if (selection.Count == 1)
{
if (selection[1] is Outlook.MailItem)
{
mailItem = (selection[1] as Outlook.MailItem);
if (mailItem != null)
{
string senderEmailAddress = mailItem.SenderEmailAddress;
What I have tried and Succeeded :- I know how to convert x500 type to SMTP using a Outlook.Recipient object. There I can get the "addressEntry" of the Recipient and obtain ExhangeUser, then go for the "PrimarySmtpAddress" of ExhangeUser. But I am not quiet sure about how to deal with SenderEmailAddress and convert it as SMTP.
Some interesting experiments :-
Since the property of "Sender" is not available in the current mailitem object, I managed to use reflection to get the property of "Sender". But When I run following code the "propertyInfo" object value is getting null. I can't understand why.
Here is the code
//...
if (mailItem != null)
{
var mailItem2 = GetNewObject(mailItem, "Sender", intArray);
//...
public static object GetNewObject(Outlook.MailItem o, string popertyName, object[] parameters)
{
try
{
PropertyInfo propertyInfo = o.GetType().GetProperty(popertyName); // This object is getting null
return propertyInfo.GetType().GetProperty(popertyName).GetValue(o,parameters) as Outlook.MailItem;
}
catch (MissingMethodException ex)
{
// discard or do something
Debug.DebugMessage(2, "AddinModule : Error in GetNewObject() : " + ex.Message);
return null;
}
}
Please advice me. Thank you.
You can obtain the AddressEntry of the sender using the Sender property like this:
Outlook.AddressEntry senderAddressEntry = mailItem.Sender;
After reading the comment from "Dmitry Streblechenko" I was able to develop a fully working solution for my self. Here is the code
private void adxRibBtnAddEmailAddress_OnClick(object sender, IRibbonControl control, bool pressed)
{
Outlook.MailItem mailItem = null;
Outlook.Recipient recipient = null;
string recipientsEmail = "";
string sendersEmail = "";
try
{
mailItem = OutlookHelper.GetSelectedMailItem();
if (mailItem != null)
{
if (mailItem.SenderEmailType == "EX")
sendersEmail = GetSenderEmailAddress(mailItem);
else
sendersEmail = mailItem.SenderEmailAddress;
if (!string.IsNullOrEmpty(sendersEmail))
{
if (sendersEmail == Globals.OLCurrentUserEmail) // Sent mail
{
recipient = mailItem.Recipients[1];
if (recipient != null)
{
recipientsEmail = OutlookHelper.GetAddress(ref recipient);
if (!string.IsNullOrEmpty(recipientsEmail))
{
// Do Something
}
}
}
else // inbox mail
{
// Do Something
}
}
}
}
catch (Exception ex)
{
Debug.DebugMessage(2, "AddinModule : Error in adxRibBtnsddemailaddress_OnClick() : " + ex.Message);
}
finally
{
if (recipient != null) Marshal.ReleaseComObject(recipient);
if (mailItem != null) Marshal.ReleaseComObject(mailItem);
Cursor.Current = Cursors.Default;
}
}
private string GetSenderEmailAddress(Outlook.MailItem oM)
{
Outlook.PropertyAccessor oPA = null;
Outlook.AddressEntry oSender = null;
Outlook.ExchangeUser oExUser = null;
string SenderID;
string senderEmailAddress;
try
{
// Create an instance of PropertyAccessor
oPA = oM.PropertyAccessor;
// Obtain PidTagSenderEntryId and convert to string
SenderID = oPA.BinaryToString(oPA.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x0C190102"));
// Obtain AddressEntry Object of the sender
oSender = Globals.ObjNS.GetAddressEntryFromID(SenderID);
oExUser = oSender.GetExchangeUser();
senderEmailAddress = oExUser.PrimarySmtpAddress;
return senderEmailAddress;
}
catch (Exception ex)
{
Debug.DebugMessage(2, "AddinModule : Error in adxRibBtnAddGenInteraction_OnClick() : " + ex.Message);
return null;
}
finally
{
if (oExUser != null) Marshal.ReleaseComObject(oExUser);
if (oSender != null) Marshal.ReleaseComObject(oSender);
if (oPA != null) Marshal.ReleaseComObject(oPA);
}
}
I try to write a Webservice that can access to my exchange-server and search for names, companys and cities. At the moment i get the names like this:
ExchangeServiceBinding esb = new ExchangeServiceBinding();
esb.UseDefaultCredentials = true;
// Create the ResolveNamesType and set
// the unresolved entry.
ResolveNamesType rnType = new ResolveNamesType();
rnType.ReturnFullContactData = true;
rnType.UnresolvedEntry = "searchname";
// Resolve names.
ResolveNamesResponseType resolveNamesResponse
= esb.ResolveNames(rnType);
ArrayOfResponseMessagesType responses
= resolveNamesResponse.ResponseMessages;
// Check the result.
if (responses.Items.Length > 0 && responses.Items[0].ResponseClass != ResponseClassType.Error)
{
ResolveNamesResponseMessageType responseMessage = responses.Items[0] as
ResolveNamesResponseMessageType;
// Display the resolution information.
ResolutionType[] resolutions = responseMessage.ResolutionSet.Resolution;
foreach (ResolutionType resolution in resolutions)
{
Console.WriteLine(
"Name: " +
resolution.Contact.DisplayName
);
Console.WriteLine(
"EmailAddress: " +
resolution.Mailbox.EmailAddress
);
if (resolution.Contact.PhoneNumbers != null)
{
foreach (
PhoneNumberDictionaryEntryType phone
in resolution.Contact.PhoneNumbers)
{
Console.WriteLine(
phone.Key.ToString() +
" : " +
phone.Value
);
}
}
Console.WriteLine(
"Office location:" +
resolution.Contact.OfficeLocation
);
Console.WriteLine("\n");
}
}
But anybody know how i can serach for Propertys like Company and Street?
EWS only has limited Directory operations if your using OnPrem Exchange then the easiest way to do this is just use LDAP and lookup Active Directory directly. The resolveName operation is meant to be used to resolve a partial number and doesn't work with any other properties. If you have Exchange 2013 then there is the FindPeople operation http://msdn.microsoft.com/en-us/library/office/jj191039(v=exchg.150).aspx which supports using a QueryString which should work if those properties are indexed. eg
EWSProxy.FindPeopleType fpType = new EWSProxy.FindPeopleType();
EWSProxy.IndexedPageViewType indexPageView = new EWSProxy.IndexedPageViewType();
indexPageView.BasePoint = EWSProxy.IndexBasePointType.Beginning;
indexPageView.Offset = 0;
indexPageView.MaxEntriesReturned = 100;
indexPageView.MaxEntriesReturnedSpecified = true;
fpType.IndexedPageItemView = indexPageView;
fpType.ParentFolderId = new EWSProxy.TargetFolderIdType();
EWSProxy.DistinguishedFolderIdType Gal = new EWSProxy.DistinguishedFolderIdType();
Gal.Id = EWSProxy.DistinguishedFolderIdNameType.directory;
fpType.QueryString = "Office";
fpType.ParentFolderId.Item = Gal;
EWSProxy.FindPeopleResponseMessageType fpm = null;
do
{
fpm = esb.FindPeople(fpType);
if (fpm.ResponseClass == EWSProxy.ResponseClassType.Success)
{
foreach (EWSProxy.PersonaType PsCnt in fpm.People)
{
Console.WriteLine(PsCnt.EmailAddress.EmailAddress);
}
indexPageView.Offset += fpm.People.Length;
}
else
{
throw new Exception("Error");
}
} while (fpm.TotalNumberOfPeopleInView > indexPageView.Offset);
Cheers
Glen
EDIT: I've posted the solution below.
I know you don't like these type of questions, but i've been struggling with this issue for half a day now.
I've written a C# code that fetches user attributes from our Active Directory using LDAP, the code works well.
The code is as follows:
DirectoryEntry dirEnt = new DirectoryEntry("LDAP://dc=dom,dc=int");
DirectorySearcher adSearch = new DirectorySearcher(dirEnt);
adSearch.SearchScope = SearchScope.Subtree;
adSearch.PageSize = 10000;
adSearch.Filter = "(&(objectClass=user))";
SearchResultCollection sColl = adSearch.FindAll();
foreach (SearchResult sResult in sColl)
{
string sConn = sResult.Properties["distinguishedName"][0].ToString();
DirectoryEntry dirEnt2 = new DirectoryEntry("LDAP://" + sConn);
...
// dirEnt2 contains ALL attributes for the user
}
I'm trying to port this code to Java, but it seems like that the technique I used in C# does not work too well in Java.
Using the following code
DirContext context;
ArrayList<String> nList = new ArrayList<String>();
Hashtable env = new Hashtable();
String username = ...;
String password = ...;
try {
env.put(Context.SECURITY_PRINCIPAL, username);
env.put(Context.SECURITY_CREDENTIALS, password);
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, ldapUri);
try {
context = new InitialDirContext(env);
} catch (NamingException e) {
throw new RuntimeException(e);
}
SearchControls ctrl = new SearchControls();
ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration enumeration = context.search("", "(objectClass=user)",
ctrl);
while (enumeration.hasMore()) {
SearchResult result = (SearchResult) enumeration.next();
Attributes attribs = result.getAttributes();
NamingEnumeration values = ((BasicAttribute)
attribs.get("distinguishedName")).getAll();
while (values.hasMore()) {
nList.add(values.next().toString());
}
}
} catch (NamingException e) {
e.printStackTrace();
}
for (String sVar : nList ){
Hashtable env2 = new Hashtable();
env2.put(Context.SECURITY_PRINCIPAL, username);
env2.put(Context.SECURITY_CREDENTIALS, password);
env2.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env2.put(Context.PROVIDER_URL, "ldap://DOM/" + sVar);
Attributes attrs = null;
try {
context = new InitialDirContext(env2);
attrs = context.getAttributes(sVar);
} catch (NamingException e) {
System.out.println(e.toString());
continue;
}
System.out.println(attrs.toString());
}
Yields that attrs only contains BASIC attributes regarding the user (such as samaccountname, displayname, etc)
and no 'email', 'telephone' or any other similar attributes.
Any help on the issue is blessed!
Here's the solution, sorry for the messy code/formatting
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.*;
import javax.naming.ldap.*;
public class UserFetch {
public static void main(String[] args) {
try{
// Activate paged results
byte[] cookie = null;
int count=0;
int total;
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.REFERRAL, "follow");
env.put(Context.SECURITY_AUTHENTICATION, "Simple");
env.put(Context.SECURITY_PRINCIPAL, "USERNAME#DOM.COM");
env.put(Context.SECURITY_CREDENTIALS, "PASSWORD");
env.put(Context.PROVIDER_URL, "ldap://DOM.COM:389");
LdapContext ctx = new InitialLdapContext(env, null);
ctx.setRequestControls(new Control[]{
new PagedResultsControl(10000, Control.CRITICAL) });
do {
// Perform the search
NamingEnumeration results =
ctx.search("dc=DOM,dc=COM", "(&(objectclass=user)(employeeNumber=*))", getSimpleSearchControls());
// Iterate over a batch of search results
while (results != null && results.hasMore()) {
// Display an entry
SearchResult entry = (SearchResult)results.next();
Attributes attrs = entry.getAttributes ();
System.out.println(attrs.get("SAMAccountName")); // Username
System.out.println("Firstname: " +
attrs.get("givenname")); // firstname
System.out.println("Lastname: " + attrs.get("sn")); // lastname
System.out.println("EmployeeID " + attrs.get("employeeID"));
System.out.println("EmployeeNumber: " +
attrs.get("employeeNumber"));
// Handle the entry's response controls (if any)
}
// Examine the paged results control response
Control[] controls = ctx.getResponseControls();
if (controls != null) {
for (int i = 0; i < controls.length; i++) {
if (controls[i] instanceof PagedResultsResponseControl) {
PagedResultsResponseControl prrc =
(PagedResultsResponseControl)controls[i];
total = prrc.getResultSize();
cookie = prrc.getCookie();
} else {
// Handle other response controls (if any)
}
}
}
// Re-activate paged results
ctx.setRequestControls(new Control[]{
new PagedResultsControl(10000, cookie, Control.CRITICAL) });
} while (cookie != null);
} catch (Exception e) {
e.printStackTrace();
}
}
public static SearchControls getSimpleSearchControls() {
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
searchControls.setTimeLimit(30000);
String[] attrIDs =
{ "SAMAccountName", "sn", "givenname", "employeeID",
"employeeNumber" };
searchControls.setReturningAttributes(attrIDs);
return searchControls;
}
}
Try setting the returned attributes on your SearchControls
ctrl.setReturningAttributes(new String[] {"email", "telephone"});