HowTo: Create a mailbox for an existing user, Create a user in AD, List AD User info.

//======================================================================================================

// CdoexmMailboxUtil -

// Exchange Mailbox and user account creation sample.

//

// This sample demonstrates the following:

// Creating a user account in AD

// Mail Enable an existing user.

// List information on an existing user.

// Note: This code is provided as a sample only, so you need to test and take responsibility

// of the code and any of its possible actions before usage. Being a sample, its provided

// for educational purposes only and is not supported in any way.

// Note: Because CDOEX is used, you must run this on the Exchange server being accessed.

// Note: Because this code uses CDOEXM, it will not run on an Exchange 2007 server. For Exchange 2007,

// you should use PowerShell instead.

// To compile:

// Set references to CDOEXM and CDOEX:

// CDOEX can be reference as this COM component: "Microsoft CDO for Exchange 2000 Library"

// Note: Setting a reference to CDOEX will generate the "CDO" and "ADODB" interops.

// If there is a preexisting ADODB interop, its usually best to remove it and let the

// referencing of CDOEX generate the ADODB interop.

// CDOEXM can be referenced as this COM component "CDO for Exchange Management"

// Note: Setting a reference to will generate the CDOEXM iterop.

// ActiveDS can be referenced as this COM component "Active DS Type Library"

// Note: Setting a reference to will generate the ActiveDS iterop.

//

// Last changed 8/19/2009

//

//======================================================================================================

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using CDOEXM;

using CDO;

using ActiveDs;

using System.DirectoryServices;

using System.EnterpriseServices;

using System.Runtime.InteropServices;

namespace ExchangePfUtil

{

    class CdoexmMailboxUtil

    {

        //-------------------------------------------------------------------------------------------------------------------------------

        // TestCreateNewUserAndCreateMailbox – Create a new account, then independantly create the mailbox for it if the account was created.

        //-------------------------------------------------------------------------------------------------------------------------------

        public static bool TestCreateNewUserAndCreateMailbox()

        {

            bool bRet = false;

            string sFistName = "FirstName";

            string sLastName = "LastName";

            string sSamName = "firstlast";

            string sCreateUserBaseContainer = "LDAP://CN=Users,DC=171751dom,DC=net";

            string sCreateMailboxBaseContainer = "LDAP://DC=171751dom,DC=net";

            string sHomeMDB = "CN=Mailbox Store (AP1-109028),CN=First Storage Group,CN=InformationStore," +

                "CN=AP1-109028,CN=Servers,CN=First Administrative Group,CN=Administrative Groups,CN=First Organization," +

                "CN=Microsoft Exchange,CN=Services,CN=Configuration," +

                "DC=171751dom,DC=net";

            string sError = "";

            string UserId = null; // "Administrator";

            string Password = null; // "xxxx";

 

            bRet = CreateUser(sSamName, sFistName, sLastName, sCreateUserBaseContainer, sHomeMDB, out sError);

            if (bRet == true)

            {

                bRet = MailEnableUser(sHomeMDB, sSamName, sCreateMailboxBaseContainer, UserId, Password, out sError);

            }

            return bRet;

        }

        //-------------------------------------------------------------------------------------------------------------------------------

        // TestCreateMailBoxForExistingUser – test existing account created in Active Directory Users and Computers – with no mailbox.

        //-------------------------------------------------------------------------------------------------------------------------------

        public static bool TestCreateMailBoxForExistingUser()

        {

            bool bRet = false;

 

            string sSamName = "firstlastExisting";

           

            string sCreateMailboxBaseContainer = "LDAP://DC=171751dom,DC=net";

            string sHomeMDB = "CN=Mailbox Store (AP1-109028),CN=First Storage Group,CN=InformationStore," +

                "CN=AP1-109028,CN=Servers,CN=First Administrative Group,CN=Administrative Groups,CN=First Organization," +

                "CN=Microsoft Exchange,CN=Services,CN=Configuration," +

                "DC=171751dom,DC=net";

            string sError = "";

            string UserId = null; // "Administrator";

            string Password = null; // "xxxx";

            bRet = MailEnableUser(sHomeMDB, sSamName, sCreateMailboxBaseContainer, UserId, Password, out sError);

            

            return bRet;

        }

        //-----------------------------------------------------------------------------------------------------------------

        // CreateUser()

        //-----------------------------------------------------------------------------------------------------------------

        private static bool CreateUser(string sSamName, string sFistName, string sLastName, string sBaseContainer, string sHomeMDB, out string sErrorMessage)

        {

            bool bRet = false;

            string sError = "";

            try

            {

                DirectoryEntry oCont = new DirectoryEntry(sBaseContainer);

                IADsContainer oDSCont = null;

                IADsUser oUser = null;

                oDSCont = oCont.NativeObject as IADsContainer;

                oUser = oDSCont.Create("user", string.Format("CN={0} {1}", sFistName, sLastName)) as IADsUser;

                oUser.Put("sn", sLastName);

                oUser.Put("givenname", sFistName);

                oUser.Put("samaccountname", sSamName);

                oUser.SetInfo();

                oUser.AccountDisabled = false;

                oUser.SetInfo();

                bRet = true;

            }

            catch (Exception ex)

            {

                sError = ex.Message;

                Console.WriteLine("Failed to create user");

                Console.WriteLine(ex.Message);

                bRet = false;

            }

            sErrorMessage = sError;

            return bRet;

        }

        //--------------------------------------------------------------------------------------------

        // MailEnableUser

        //--------------------------------------------------------------------------------------------

        private static bool MailEnableUser(string sHomeMDB, string sSamName, string AdLdapPath, string AdUserId, string AdPassword, out string sErrorMessage)

        {

            string sError = "";

            bool bRet = false;

            DirectoryEntry oDirectoryEntryServer = new DirectoryEntry(AdLdapPath); //, null, null, AuthenticationTypes.Secure);

            try

            {

                DirectorySearcher oDirectorySearcher = new DirectorySearcher(oDirectoryEntryServer);

                oDirectorySearcher.Filter = "(SAMAccountName=" + sSamName + ")";

                SearchResult LDAPresult = oDirectorySearcher.FindOne();

                DirectoryEntry oDirectoryEntry = LDAPresult.GetDirectoryEntry();

                ActiveDs.IADsUser oUser = (IADsUser)oDirectoryEntry.NativeObject;

  //IMailboxStore oMailBox = null;

                bRet = CreateMailbox(oUser, sHomeMDB, out sError);

                bRet = true;

            }

            catch (Exception ex)

            {

                sError = ex.Message;

                Console.WriteLine("Could not get directory entry for user.");

                Console.WriteLine(ex.Message);

                bRet = false;

            }

            sErrorMessage = sError;

            return bRet;

        }

        //---------------------------------------------------------------------------------------------------

        // CreateMailbox

        //---------------------------------------------------------------------------------------------------

        private static bool CreateMailbox(IADsUser oUser, string sHomeMDB, out string sErrorMessage)

        {

            string sError = "";

            bool bRet = false;

            IMailboxStore oMailBox = null;

            try

            {

                oMailBox = (IMailboxStore)oUser;

                oMailBox.CreateMailbox(sHomeMDB);

                oUser.SetInfo();

                bRet = true;

            }

            catch (Exception ex)

            {

                sError = ex.Message;

                Console.WriteLine("Could not create mailbox.");

                Console.WriteLine(ex.Message);

                bRet = false;

            }

            Marshal.ReleaseComObject(oMailBox);

            sErrorMessage = sError;

            return bRet;

        }

   //---------------------------------------------------------------------------------------------------

        // UserInfo

        // Display info on a user account in AD.

        //---------------------------------------------------------------------------------------------------

        public static bool UserInfo(string sSamName, string AdLdapPath, string AdUserId, string AdPassword, out string sErrorMessage)

        {

            string sError = "";

            bool bRet = false;

            DirectoryEntry oDirectoryEntryServer = new DirectoryEntry(AdLdapPath); //, null, null, AuthenticationTypes.Secure);

            try

            {

                DirectorySearcher oDirectorySearcher = new DirectorySearcher(oDirectoryEntryServer);

                oDirectorySearcher.Filter = "(SAMAccountName=" + sSamName + ")";

                SearchResult LDAPresult = oDirectorySearcher.FindOne();

                DirectoryEntry oDirectoryEntry = LDAPresult.GetDirectoryEntry();

                ActiveDs.IADsUser oUser = (IADsUser)oDirectoryEntry.NativeObject;

                //IMailboxStore oMailBox = null;

                //Console.WriteLine(string.Format("distinguishedName: {0}", LDAPresult.Properties["distinguishedName"] ));

                Console.WriteLine(string.Format("FullName: {0}", oUser.FullName.ToString()));

                Console.WriteLine(string.Format("FirstName: {0}", oUser.FirstName.ToString()));

                Console.WriteLine(string.Format("LastName: {0}", oUser.LastName.ToString()));

                Console.WriteLine(string.Format("EmailAddress: {0}", oUser.EmailAddress.ToString()));

                Console.WriteLine(string.Format("ADsPath: {0}", oUser.ADsPath.ToString()));

                Console.WriteLine(string.Format("AccountDisabled: {0}", oUser.AccountDisabled.ToString()));

                bRet = true;

            }

            catch (Exception ex)

            {

                sError = ex.Message;

                Console.WriteLine("Error trying to find user.");

   Console.WriteLine(ex.Message);

                bRet = false;

            }

            sErrorMessage = sError;

            return bRet;

        }

    }

}

 

Here are some related links:

XADM: The CDOEXM IMailboxStore::CreateMailbox() or IMailboxStore::MoveMailbox() Method Fails

https://support.microsoft.com/kb/317234/

How to set Exchange Server 2000 and 2003 mailbox rights at the time of mailbox creation

https://support.microsoft.com/kb/304935

How to programmatically create a mailbox for an existing user in the Active Directory by using CDOEXM

https://support.microsoft.com/kb/327079

How to create a mailbox-enabled recipient by using Visual C#

https://support.microsoft.com/kb/313114

HOWTO: Using CDOEXM in ASP.NET (.NET Framework 2.0 Walkthrough)

https://blogs.msdn.com/mstehle/archive/2007/05/11/howto-using-cdoexm-in-asp-net-net-framework-2-0-walkthrough.aspx