Create Exchange Account With C#

This article will provide C# code that will allow you to leverage the Exchange Management Shell to add a new Microsoft Exchange 2010/2013 Mailbox and Active Directory Account. In order to use the code below, you must have the Exchange Management tools installed on the machine which will be running this code. Exchange Management Tools installation instructions can be found here. The code below can be used in creating either a console or windows forms application using SharpDevelop IDE. In creating your own application, you will want to ensure you have imported the required libraries using the code directly below.

 * Created by SharpDevelop.
 * User: mmarable
 * Date: 2/25/2015
 * Time: 10:35 AM
using System;
using System.Security;
using System.Windows.Forms;
using System.Management.Automation;
using System.Management.Automation.Runspaces;

Once you have imported all the required libraries, simply paste the function below in your code and start using it as needed.

public Boolean CreateUserMailbox(string FirstName, string LastName, string Alias, string PassWord, string DomainName, string OrganizationalUnit)
			string Name = FirstName + " " + LastName;
			string PrincipalName = Alias + "@" + DomainName;

			Boolean success = false;
			RunspaceConfiguration rsConfig = RunspaceConfiguration.Create();
			SecureString spassword = new SecureString();

			foreach (char c in PassWord) {

			PSSnapInException snapInException = null;
			PSSnapInInfo info = rsConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out snapInException);
			Runspace myRunSpace = RunspaceFactory.CreateRunspace(rsConfig);
			Pipeline pipeLine = myRunSpace.CreatePipeline();

			Command myCommand = new Command("New-MailBox");
			myCommand.Parameters.Add("Name", Name);
			myCommand.Parameters.Add("Alias", Alias);
			myCommand.Parameters.Add("UserPrincipalName", PrincipalName);
			myCommand.Parameters.Add("Confirm", false);
			myCommand.Parameters.Add("SamAccountName", Alias);
			myCommand.Parameters.Add("FirstName", FirstName);
			myCommand.Parameters.Add("LastName", LastName);
			myCommand.Parameters.Add("Password", spassword);
			myCommand.Parameters.Add("ResetPasswordOnNextLogon", false);
			myCommand.Parameters.Add("OrganizationalUnit", OrganizationalUnit);
			catch (Exception ex)
				lblError.Text = ex.Message;
				success = true;
			return success;
Did you find this article useful? Why not share it with your friends?

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.