在 C# 中创建交换邮箱 [英] Create exchange mailbox in c#

查看:64
本文介绍了在 C# 中创建交换邮箱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 c# 在 Exchange Server 2013 中创建邮箱.

I want to create Mailbox in exchange server 2013 using c# .

我尝试了很多代码,但每一个都得到一个错误,表明没有明显的解决方案来解决它.

I tried lots of codes but each one gets an error that there is no obvious solution to solve it.

我的代码是

public static Boolean CreateUser(string FirstName, string LastName, string Alias,string PassWord, string DomainName, string OrganizationalUnit)
    {
        string Name = FirstName + " " + LastName;
        string PrincipalName = FirstName + "." + LastName + "@" + DomainName;

        Boolean success = false;
        string consolePath = @"C:\Program Files\Microsoft\Exchange Server\V15\bin\exshell.psc1";
        PSConsoleLoadException pSConsoleLoadException = null;
        RunspaceConfiguration rsConfig = RunspaceConfiguration.Create(consolePath, out pSConsoleLoadException);
        SecureString spassword = new SecureString();
        spassword.Clear();

        foreach (char c in PassWord)
        {
            spassword.AppendChar(c);
        }

        PSSnapInException snapInException = null;
        Runspace myRunSpace = RunspaceFactory.CreateRunspace(rsConfig);
        myRunSpace.Open();
        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", true);
        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);
        pipeLine.Commands.Add(myCommand);
        pipeLine.Invoke();     // got an error here
        myRunSpace.Dispose();
       }

并调用它:

Boolean Success = CreateUser("firstname", "lastName", "aliasName", "AAaa12345", "mydomain.com", "mydomain.com/Users");

我收到此错误:

Additional information: The term 'New-MailBox' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

我测试的另一个代码是:

and another code that I test is:

string userName = "administrator";
        string password = "mypass";
        System.Security.SecureString securePassword = new System.Security.SecureString();
        foreach (char c in password)
        {
            securePassword.AppendChar(c);
        }
        PSCredential credential = new PSCredential(userName, securePassword);
        WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri("https://{my server IP}/POWERSHELL/Microsoft.Exchange"),
        "http://schemas.microsoft.com/powershell/Microsoft.Exchange",
        credential);

        connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;
        connectionInfo.SkipCACheck = true;
        connectionInfo.SkipCNCheck = true;
        connectionInfo.MaximumConnectionRedirectionCount = 2;

        using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
        {
            runspace.Open();
            using (PowerShell powershell = PowerShell.Create())
            {
                powershell.Runspace = runspace;
                //Create the command and add a parameter
                powershell.AddCommand("Get-Mailbox");
                powershell.AddParameter("RecipientTypeDetails", "UserMailbox");
                //Invoke the command and store the results in a PSObject collection
                Collection<PSObject> results = powershell.Invoke();
                //Iterate through the results and write the DisplayName and PrimarySMTP
                //address for each mailbox
                foreach (PSObject result in results)
                {
                    Console.WriteLine(
                        string.Format("Name: { 0}, PrimarySmtpAddress: { 1}",

                result.Properties["DisplayName"].Value.ToString(),
                result.Properties["PrimarySmtpAddress"].Value.ToString()

                ));

                }
            }
        }

我收到这个错误

Additional information: Connecting to remote server {Server IP Address} failed with the following error message : [ClientAccessServer=WIN-FRP2TC5SKRG,BackEndServer=,RequestId=460bc5fe-f809-4454-8472-ada97eacb9fb,TimeStamp=4/6/2016 6:23:28 AM] Access is denied. For more information, see the about_Remote_Troubleshooting Help topic.

我想我给了我的管理员用户所需的所有权限,并且防火墙已关闭,但它还不起作用.

I think I gave every permission which is needed to my administrator user and firewall is off but it doesn't work yet.

任何帮助或提示!!谢谢

Any help or hint !! thanks

推荐答案

我取消选中prefer 32-bit"并将平台目标更改为 x64,问题解决了.

I unchecked "prefer 32-bit" and changed platform target to x64, the problem was solved.

使用以下代码:

 public class ExchangeShellExecuter
{

    public Collection<PSObject> ExecuteCommand(Command command)
    {
        RunspaceConfiguration runspaceConf = RunspaceConfiguration.Create();
        PSSnapInException PSException = null;
        PSSnapInInfo info = runspaceConf.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out PSException);
        Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConf);
        runspace.Open();
        Pipeline pipeline = runspace.CreatePipeline();
        pipeline.Commands.Add(command);
        Collection<PSObject> result = pipeline.Invoke();
        return result ;
    }
}
    public class ExchangeShellCommand
{
    public Command NewMailBox(string userLogonName,string firstName,string lastName,string password
        ,string displayName,string organizationUnit = "mydomain.com/Users", 
        string database = "Mailbox Database 1338667540", bool resetPasswordOnNextLogon = false)
    {
        try
        {
            SecureString securePwd = ExchangeShellHelper.StringToSecureString(password);
            Command command = new Command("New-Mailbox");
            var name = firstName + " " + lastName;

            command.Parameters.Add("FirstName", firstName);
            command.Parameters.Add("LastName", lastName);
            command.Parameters.Add("Name", name);

            command.Parameters.Add("Alias", userLogonName);
            command.Parameters.Add("database", database);
            command.Parameters.Add("Password", securePwd);
            command.Parameters.Add("DisplayName", displayName);
            command.Parameters.Add("UserPrincipalName", userLogonName+ "@mydomain.com");
            command.Parameters.Add("OrganizationalUnit", organizationUnit);
            //command.Parameters.Add("ResetPasswordOnNextLogon", resetPasswordOnNextLogon);

            return command;
        }
        catch (Exception)
        {

            throw;
        }
    }

    public Command AddEmail(string email, string newEmail)
    {
        try
        {
            Command command = new Command("Set-mailbox");
            command.Parameters.Add("Identity", email);
            command.Parameters.Add("EmailAddresses", newEmail);
            command.Parameters.Add("EmailAddressPolicyEnabled", false);

            return command;
        }
        catch (Exception)
        {

            throw;
        }
        //
    }

    public Command SetDefaultEmail(string userEmail, string emailToSetAsDefault)
    {
        try
        {
            Command command = new Command("Set-mailbox");
            command.Parameters.Add("Identity", userEmail);
            command.Parameters.Add("PrimarySmtpAddress", emailToSetAsDefault);

            return command;
        }
        catch (Exception)
        {

            throw;
        }
        //PrimarySmtpAddress
    }


}

并运行:

 var addEmailCommand = new ExchangeShellCommand().AddEmail("unos4@mydomain.com","unos.bm65@yahoo.com");
        var res2 = new ExchangeShellExecuter().ExecuteCommand(addEmailCommand);

        var emailDefaultCommand = new ExchangeShellCommand().AddSetDefaultEmail("unos4@mydomain.com", "unos.bm65@yahoo.com");
        var res3 = new ExchangeShellExecuter().ExecuteCommand(emailDefaultCommand);

这篇关于在 C# 中创建交换邮箱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆