Sunday, March 15, 2009

How to email all AD (active directory) users from sharepoint event handlers

Sharepoint is normally (or should be) installed into server PCs. And the event handler features are also installed into servers. But AD users use sharepoint from their client PCs. In this case, program fails to log into the domain if you try to retrieve information directly. Normally this code is good enough to retrive all AD users:

ArrayList employeeEmailAddresses = new ArrayList();
string filter = "(&(objectCategory=person)(objectClass=user)(sn=*))";
DirectorySearcher search = new DirectorySearcher(filter);
foreach (SearchResult result in search.FindAll())
{
DirectoryEntry entry = result.GetDirectoryEntry();
if (entry.Properties["mail"].Value != null)
{
string str = entry.Properties["mail"].Value.ToString();
employeeEmailAddresses.Add(str);
}

}

But if you are trying to get information from sharepoint event handlers using the above code block, program will throw exception at search.FindAll() :

COMEXCEPTION was caught: {"An operations error occurred.\r\n"}

In order to solve this, you need to manually log in the program into the AD using the credentials of an existing AD user. Then, the program can read all the informations from AD.

you can use this method to get all the users from AD:

private ArrayList getEmployeeMailAddresses()
{
ArrayList employeeEmailAddresses = new ArrayList();
try
{
string filter = "(&(objectCategory=person)(objectClass=user)(sn=*))";

using (DirectoryEntry root = new DirectoryEntry("LDAP://domainName","userName","password", AuthenticationTypes.Secure))
{
using (DirectorySearcher searcher = new DirectorySearcher(root))
{
searcher.ReferralChasing = ReferralChasingOption.All;
searcher.SearchScope = SearchScope.Subtree;
searcher.Filter = filter;

foreach (SearchResult result in searcher.FindAll())
{
DirectoryEntry entry = result.GetDirectoryEntry();
if (entry.Properties["mail"].Value != null)
{
string str = entry.Properties["mail"].Value.ToString();
employeeEmailAddresses.Add(str);
}

}
}

}
}
catch (Exception ex)
{
}

return employeeEmailAddresses;
}

This line: DirectoryEntry("LDAP://domainName","userName","password", AuthenticationTypes.Secure)) will login the program into the appropriate domain, then you can get informations for all AD users. After getting the arraylist that contains all the users, you can mail all of them using this method:

private void sendEmail(string htmlBody, ArrayList employeeEmailAddresses, string itemCreator, string subject)
{
AlternateView avHtml = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html);
MailMessage m1 = new MailMessage();
m1.AlternateViews.Add(avHtml);

for (int i = 0; i < employeeEmailAddresses.Count; i++)
{
m1.To.Add(new MailAddress(employeeEmailAddresses[i].ToString()));
}
m1.Subject = subject;


SmtpClient client = new SmtpClient("smtpclientaddress");
client.Send(m1);

}

1 comment:

karlzzzon said...

thank you very match for this post