简体   繁体   中英

How do I make mail contacts in Microsoft Exchange?

I'm looking for a alternate way to create mail contacts in Microsoft Exchange using C#, typically using the API of EWS for a Microsoft Exchange 2016 instead of relying on the Powershell command New-MailContact . I know there is a very similar question on SO, but it has been posted in 2012, so hopefully something new came up inbetween.

If this is not the case, it there any way to create a contact in Active Directory that would be reflected as a mail contact in Exchange?

You will likely need to use the Exchange Management Shell . The code will look similar to this snippet:

using System;
using System.Security;
using System.Management.Automation;
using System.Management.Automation.Runspaces;

public bool CreateMailContact(string firstName, string lastName, string alias, string email)
    {
      string fullName = firstName + " " + lastName;
      string address = "SMTP:" + ExternalEmail;

      RunspaceConfiguration runspacesConfig = RunspaceConfiguration.Create();

      PSSnapInException snapInException = null;
      PSSnapInInfo info = runspaceConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.SnapIn", out snapInException);
      Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfig);
      runspace.Open();
      Pipeline pipeline = runspace.CreatePipeline();

      Command createCommand = new Command("New-MailContact");
      createCommand.Parameters.Add("ExternalEmailAddress", address);
      createCommand.Parameters.Add("Name", name);
      createCommand.Parameters.Add("Alias", alias);
      createCommand.Parameters.Add("FirstName", firstName);
      createCommand.Parameters.Add("LastName", lastName);
      pipeline.Commands.Add(createCommand);
      try
      {
        pipeline.Invoke();
      }
      catch (Exception ex)
      {
        Console.WriteLine("An error occurred.")
      }
      finally
      {
        runspace.Dispose();
        return true;
      }
      return false;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM