C#创建邮箱

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.DirectoryServices;
using Microsoft.PowerShell.Commands;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Security;
using System.Configuration;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Management;
using System.Management.Instrumentation;
using System.Security.Principal;
using System.Management.Automation.Runspaces;
using System.Management.Automation;
using System.Text;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Runtime.InteropServices;
namespace Testmail
{
    /// <summary>
    /// WebService1 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
    // [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
        private static IntPtr _userToken = IntPtr.Zero;
        private static WindowsImpersonationContext _impersonationContext = null;
        [WebMethod]
        public void AddPowerUser(string uname, string pword, string email)
        {
          
            //Create a runspace for your cmdlets to run and include the Exchange Management SnapIn...
            try
            {
                RunspaceConfiguration runspaceConf = RunspaceConfiguration.Create();

                PSSnapInException PSException = null;

                PSSnapInInfo info = runspaceConf.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out PSException);
                //登陆邮箱服务器
                BeginImpersonation(ConfigurationManager.AppSettings["Domain"].Trim());
                using (Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConf))
                {
                    try
                    {
                        runspace.Open();
                        Pipeline pipeline = runspace.CreatePipeline();
                        Command Command = new Command("New-Mailbox");
                        // Command.Parameters.Add("Name", uname);
                        // now you must pass secure string
                        char[] passwordChars = pword.ToCharArray();
                        SecureString password = new SecureString();
                        foreach (char c in passwordChars)
                        {
                            password.AppendChar(c);
                        }
                        // these are the minimum parameters required
                      
                        //Command.Parameters.Add("LastName", uname);
                        //Command.Parameters.Add("Initials", "");
                        //Command.Parameters.Add("FirstName", uname);
                        //Command.Parameters.Add("DisplayName", uname + "*" + "flag");

                        Command.Parameters.Add("-UserPrincipalName", email);
                        //Command.Parameters.Add("SamAccountName", uname);
                        Command.Parameters.Add("-Alias", uname);
                        Command.Parameters.Add("-Name", uname);
                        Command.Parameters.Add("-Password", password);
                        Command.Parameters.Add("-Database", ConfigurationManager.AppSettings["Database"].Trim());
                        Command.Parameters.Add("-OrganizationalUnit", ConfigurationManager.AppSettings["OrganizationalUnit"].Trim());
                        Command.Parameters.Add("-ResetPasswordOnNextLogon", true);
                        //Command.Parameters.Add("-DomainController", ConfigurationManager.AppSettings["DomainController"].Trim());
                        //command.Parameters.Add("Password", password);
                        //command.Parameters.Add("UserPrincipalName", email);
                        //command.Parameters.Add("Database", ConfigurationManager.AppSettings["Database"].Trim());  //WIN2K3-EXH2007/Mailbox Database
                        //command.Parameters.Add("OrganizationalUnit", ConfigurationManager.AppSettings["OrganizationalUnit"].Trim());  //Test
                        //set other mailbox parameters here
                        pipeline.Commands.Add(Command);
                        Console.WriteLine("prepared the parameters...");
                        Console.WriteLine("start to calling PowerShell...");
                        try
                        {
                            Collection<PSObject> result = pipeline.Invoke();
                        }
                        catch (Exception exx)
                        {

                            throw new Exception(exx.Message);
                        }

                        // Check for errors in the pipeline and throw an exception if necessary.
                        //if (pipeline.Error != null && pipeline.Error.Count > 0)
                        //{
                        //    StringBuilder pipelineError = new StringBuilder();
                        //    pipelineError.AppendFormat("Error calling New-Mailbox.");
                        //    foreach (object item in pipeline.Error.ReadToEnd())
                        //    {
                        //        pipelineError.AppendFormat("{0}\n", item.ToString());
                        //    }
                        //    throw new Exception(pipelineError.ToString());
                        //}
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    finally
                    {
                        runspace.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        [DllImport("advapi32.dll", SetLastError = true)]
        public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
        public static void BeginImpersonation(string domain)
        {
            //Please change the User Name and Password
            string UserName = System.Configuration.ConfigurationManager.AppSettings["ExchangeAdminUser"];
            string Password = System.Configuration.ConfigurationManager.AppSettings["ExchangeAdminPwd"];

            EndImpersonation();

            bool success = LogonUser(
                    UserName,
                    domain,
                    Password,
                    2,
                    0,
                    ref _userToken);

            // Did it work?
            if (!success) throw new Exception(string.Format("LogonUser returned error {0}", System.Runtime.InteropServices.Marshal.GetLastWin32Error()));

            WindowsIdentity fakeId = new WindowsIdentity(_userToken);
            _impersonationContext = fakeId.Impersonate();

        }
        public static void EndImpersonation()
        {
            if (_impersonationContext != null)
            {
                try
                {
                    _impersonationContext.Undo();
                }
                finally
                {
                    _impersonationContext.Dispose();
                    _impersonationContext = null;
                }
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值