Monday, November 10, 2008

Get email address from mailbox alias using EWS

Here is a cool Exchange Web Service, Resolve Name, that you can use to get the email address from your mailbox alias.

This is a sample function:


private string GetEmailAddressFromUser(string alias)
{
try
{
// SSL Certificate validation
ServicePointManager.ServerCertificateValidationCallback =
delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
// Aceptamos el certificado sin mirar
return true;
};

// Initialize the EWS Service
ExchangeServiceBinding ewsService = new ExchangeServiceBinding();

// User's Credentials
ewsService.Credentials = new NetworkCredential(m_Service_Credential_User, m_Service_Credential_Password, m_Service_Credential_Domain);

// EWS Service URL and Proxy
ewsService.Url = m_Service_Url;
ewsService.Proxy = this.GetProxy();

// Resolve Name Parameters
ResolveNamesType resolveNamesType = new ResolveNamesType();
resolveNamesType.ReturnFullContactData = true;
resolveNamesType.UnresolvedEntry = alias;

// Invoke EWS Service
ResolveNamesResponseType response = ewsService.ResolveNames(resolveNamesType);

// Get the result
ResolveNamesResponseMessageType root =
(ResolveNamesResponseMessageType)response.ResponseMessages.Items[0];

// Check the result
if (root.ResponseClass != ResponseClassType.Success)
{
// Throw an Exception
throw new ApplicationException(string.Format("{0}.{1}.{2}", root.ResponseClass, root.ResponseCode, root.MessageText));
}
else
{
// Get the email address
return root.ResolutionSet.Resolution[0].Mailbox.EmailAddress;
}
}
catch (Exception ex)
{
throw ex;
}
}

No comments: