Adicionar e remover representantes usando o EWS no ExchangeAdd and remove delegates by using EWS in Exchange

Saiba como adicionar ou remover representantes de caixas de correio dos usuários usando a API gerenciada do EWS ou o EWS no Exchange.Learn how to add delegates to or remove delegates from users' mailboxes by using the EWS Managed API or EWS in Exchange.

Você pode usar a API gerenciada do EWS ou o EWS para permitir que os representantes atuem em nome de um proprietário da caixa de correio ou removam o acesso de um representante a uma caixa de correio.You can use the EWS Managed API or EWS to enable delegates to act on behalf of a mailbox owner or remove a delegate's access to a mailbox. Os usuários adicionados como um representante e recebem permissões podem executar tarefas em nome do proprietário da caixa de correio.Users who are added as a delegate, and are given permissions, can perform tasks on behalf of the mailbox owner. Por exemplo, eles podem criar e enviar convites de reunião, enviar emails e responder a solicitações de reunião no nome do proprietário da caixa de correio.For example, they can create and send meeting invitations, send emails, and respond to meeting requests on the mailbox owner's behalf.

Tabela 1. Métodos da API gerenciada do EWS e operações do EWS para adicionar e remover representantesTable 1. EWS Managed API methods and EWS operations for adding and removing delegates

TarefaTask Método de API gerenciada do EWSEWS Managed API method Operação do EWSEWS operation
Adicionar representantesAdd delegates
ExchangeService. adddelegatesExchangeService.AddDelegates
AddDelegateAddDelegate
Remover representantesRemove delegates
ExchangeService. RemoveDelegatesExchangeService.RemoveDelegates
RemoveDelegateRemoveDelegate

Após a concessão de permissões a uma pasta para um representante, elas podem atuar nos itens da pasta e em todas as subpastas, de acordo com suas permissões de representante.After a delegate is granted permissions to a folder, they can act on items in the folder and any subfolders, according to their delegate permissions. As permissões para representantes só se aplicam a subpastas criadas depois que o acesso de representante foi concedido.Permissions for delegates only apply to subfolders that are created after the delegate access was granted. Para atualizar permissões de pasta para pastas pré-existentes ou outras pastas, confira definir permissões de pasta para outro usuário usando o EWS no Exchange.To update folder permissions for pre-existing folders, or other folders, see Set folder permissions for another user by using EWS in Exchange.

Observe que os representantes só podem ser adicionados às contas habilitadas para caixa de correio, incluindo grupos de segurança habilitados para email.Note that delegates can only be added to mailbox-enabled accounts, including mail-enabled security groups. Por padrão, uma única chamada de acesso de representante do EWS pode acessar um máximo de 255 diferentes caixas de correio.By default, a single EWS delegate access call can access a maximum of 255 different mailboxes.

Adicionar representantes usando a API gerenciada do EWSAdd delegates by using the EWS Managed API

Você pode adicionar representantes a uma caixa de correio usando o método Adddelegas da API gerenciada do EWS.You can add delegates to a mailbox by using the AddDelegates EWS Managed API method. Neste exemplo, um novo objeto de calendário, contato e email DelegateUser é criado, e cada representante recebe permissões de Editor para suas respectivas pastas.In this example, a new calendar, contact, and email DelegateUser object is created, and each delegate is given Editor permissions for their respective folder. Você pode modificar o exemplo para adicionar um representante a qualquer uma das pastas especificadas pelas Propriedades DelegatePermissions, e você pode definir as permissões para qualquer um dos valores especificados pela enumeração DelegateFolderPermissionLevel .You can modify the example to add a delegate to any of the folders specified by the DelegatePermissions properties, and you can set the permissions to any of the values specified by the DelegateFolderPermissionLevel enumeration.

Este exemplo pressupõe que o serviço é um objeto ExchangeService válido para o proprietário da caixa de correio e que o usuário foi autenticado em um servidor Exchange.This example assumes that service is a valid ExchangeService object for the mailbox owner, and that the user has been authenticated to an Exchange server.

public static Collection<DelegateUserResponse> AddDelegates(ExchangeService service)
{
    // Create a list to hold the new delegates to add.
    List<DelegateUser> newDelegates = new System.Collections.Generic.List<DelegateUser>();
    // Create a new delegate that has editor access to the mailbox owner's Calendar folder.
    DelegateUser calendarDelegate = new DelegateUser("calendardelegate@contoso.com");
    calendarDelegate.Permissions.CalendarFolderPermissionLevel = DelegateFolderPermissionLevel.Editor;
    // Add the delegate to the list of new delegates.
    newDelegates.Add(calendarDelegate);
    // Create a new delegate that has editor access to the mailbox owner's Contacts folder.
    DelegateUser contactDelegate = new DelegateUser("contactdelegate@contoso.com");
    contactDelegate.Permissions.ContactsFolderPermissionLevel = DelegateFolderPermissionLevel.Editor;
    // Add the delegate to the list of new delegates.
    newDelegates.Add(contactDelegate);
            
    // Create a new delegate that has editor access to the mailbox owner's Inbox folder.
    DelegateUser emailDelegate = new DelegateUser("emaildelegate@contoso.com");
    emailDelegate.Permissions.InboxFolderPermissionLevel = DelegateFolderPermissionLevel.Editor;
    // Add the delegate to the list of new delegates.
    newDelegates.Add(emailDelegate);
    // Create a mailbox object that represents the mailbox owner.
    Mailbox mailbox = new Mailbox("primary@contoso.com");
    // Call the AddDelegates method to add the delegates to the target mailbox.
    Collection<DelegateUserResponse> response = service.AddDelegates(mailbox, MeetingRequestsDeliveryScope.DelegatesAndSendInformationToMe, newDelegates);
            
    foreach (DelegateUserResponse resp in response)
    {
        // Print out the result and the last eight characters of the item ID.
        Console.WriteLine("For delegate " + resp.DelegateUser.UserId.PrimarySmtpAddress.ToString());
        Console.WriteLine("Result: {0}", resp.Result);
        Console.WriteLine("Error Code: {0}", resp.ErrorCode);
        Console.WriteLine("ErrorMessage: {0}\r\n", resp.ErrorMessage);
        Console.WriteLine("\r\n");
    }
    return response;
}

Adicionar representantes usando o EWSAdd delegates by using EWS

O exemplo de código a seguir mostra como adicionar representantes de calendário, contato e email separados usando a operação do EWS AddDelegate .The following code example shows how to add separate calendar, contact, and email delegates by using the AddDelegate EWS operation. A caixa de correio a ser modificada é especificada pelo elemento Mailbox , e as configurações de permissão para cada representante estão contidas no elemento DelegateUser .The mailbox to modify is specified by the Mailbox element, and the permission settings for each delegate are contained in the DelegateUser element. Cada um dos representantes recebeu permissões de editor para a pasta de destino.Each of the delegates has been granted Editor permissions to their target folder.

Essa é também a solicitação XML que a API gerenciada do EWS envia quando você usa o método Adddelegates para adicionar representantes.This is also the XML request that the EWS Managed API sends when you use the AddDelegates method to add delegates.

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xmlns:m="https://schemas.microsoft.com/exchange/services/2006/messages"
               xmlns:t="https://schemas.microsoft.com/exchange/services/2006/types"
               xmlns:soap="https://schemas.xmlsoap.org/soap/envelope/">
  <soap:Header>
    <t:RequestServerVersion Version="Exchange2007_SP1" />
  </soap:Header>
  <soap:Body>
    <m:AddDelegate>
      <m:Mailbox>
        <t:EmailAddress>primary@contoso.com</t:EmailAddress>
      </m:Mailbox>
      <m:DelegateUsers>
        <t:DelegateUser>
          <t:UserId>
            <t:PrimarySmtpAddress>calendardelegate@contoso.com</t:PrimarySmtpAddress>
          </t:UserId>
          <t:DelegatePermissions>
            <t:CalendarFolderPermissionLevel>Editor</t:CalendarFolderPermissionLevel>
            <t:TasksFolderPermissionLevel>None</t:TasksFolderPermissionLevel>
            <t:InboxFolderPermissionLevel>None</t:InboxFolderPermissionLevel>
            <t:ContactsFolderPermissionLevel>None</t:ContactsFolderPermissionLevel>
            <t:NotesFolderPermissionLevel>None</t:NotesFolderPermissionLevel>
            <t:JournalFolderPermissionLevel>None</t:JournalFolderPermissionLevel>
          </t:DelegatePermissions>
          <t:ReceiveCopiesOfMeetingMessages>false</t:ReceiveCopiesOfMeetingMessages>
          <t:ViewPrivateItems>false</t:ViewPrivateItems>
        </t:DelegateUser>
        <t:DelegateUser>
          <t:UserId>
            <t:PrimarySmtpAddress>contactdelegate@contoso.com</t:PrimarySmtpAddress>
          </t:UserId>
          <t:DelegatePermissions>
            <t:CalendarFolderPermissionLevel>None</t:CalendarFolderPermissionLevel>
            <t:TasksFolderPermissionLevel>None</t:TasksFolderPermissionLevel>
            <t:InboxFolderPermissionLevel>None</t:InboxFolderPermissionLevel>
            <t:ContactsFolderPermissionLevel>Editor</t:ContactsFolderPermissionLevel>
            <t:NotesFolderPermissionLevel>None</t:NotesFolderPermissionLevel>
            <t:JournalFolderPermissionLevel>None</t:JournalFolderPermissionLevel>
          </t:DelegatePermissions>
          <t:ReceiveCopiesOfMeetingMessages>false</t:ReceiveCopiesOfMeetingMessages>
          <t:ViewPrivateItems>false</t:ViewPrivateItems>
        </t:DelegateUser>
        <t:DelegateUser>
          <t:UserId>
            <t:PrimarySmtpAddress>emaildelegate@contoso.com</t:PrimarySmtpAddress>
          </t:UserId>
          <t:DelegatePermissions>
            <t:CalendarFolderPermissionLevel>None</t:CalendarFolderPermissionLevel>
            <t:TasksFolderPermissionLevel>None</t:TasksFolderPermissionLevel>
            <t:InboxFolderPermissionLevel>Editor</t:InboxFolderPermissionLevel>
            <t:ContactsFolderPermissionLevel>None</t:ContactsFolderPermissionLevel>
            <t:NotesFolderPermissionLevel>None</t:NotesFolderPermissionLevel>
            <t:JournalFolderPermissionLevel>None</t:JournalFolderPermissionLevel>
          </t:DelegatePermissions>
          <t:ReceiveCopiesOfMeetingMessages>false</t:ReceiveCopiesOfMeetingMessages>
          <t:ViewPrivateItems>false</t:ViewPrivateItems>
        </t:DelegateUser>
      </m:DelegateUsers>
      <m:DeliverMeetingRequests>DelegatesAndSendInformationToMe</m:DeliverMeetingRequests>
    </m:AddDelegate>
  </soap:Body>
</soap:Envelope>

O servidor responde à solicitação Adddelegar com uma mensagem AddDelegateResponse que inclui um valor de elemento ResponseCode de NOERROR, que indica que os representantes foram criados com êxito.The server responds to the AddDelegate request with an AddDelegateResponse message that includes a ResponseCode element value of NoError, which indicates that the delegates were successfully created.

<?xml version="1.0" encoding="utf-8"?>
<s:Envelope xmlns:s="https://schemas.xmlsoap.org/soap/envelope/">
  <s:Header>
    <h:ServerVersionInfo MajorVersion="15"
                         MinorVersion="0"
                         MajorBuildNumber="888"
                         MinorBuildNumber="9"
                         Version="V2_10"
                         xmlns:h="https://schemas.microsoft.com/exchange/services/2006/types"
                         xmlns="https://schemas.microsoft.com/exchange/services/2006/types"
                         xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
  </s:Header>
  <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <m:AddDelegateResponse ResponseClass="Success"
                           xmlns:m="https://schemas.microsoft.com/exchange/services/2006/messages"
                           xmlns:t="https://schemas.microsoft.com/exchange/services/2006/types">
      <m:ResponseCode>NoError</m:ResponseCode>
      <m:ResponseMessages>
        <m:DelegateUserResponseMessageType ResponseClass="Success">
          <m:ResponseCode>NoError</m:ResponseCode>
          <m:DelegateUser>
            <t:UserId>
              <t:SID>S-1-5-21-1337771579-694202782-848329751-1535221</t:SID>
              <t:PrimarySmtpAddress>calendardelegate@contoso.com</t:PrimarySmtpAddress>
              <t:DisplayName>calendardelegate</t:DisplayName>
            </t:UserId>
            <t:ReceiveCopiesOfMeetingMessages>false</t:ReceiveCopiesOfMeetingMessages>
            <t:ViewPrivateItems>false</t:ViewPrivateItems>
          </m:DelegateUser>
        </m:DelegateUserResponseMessageType>
        <m:DelegateUserResponseMessageType ResponseClass="Success">
          <m:ResponseCode>NoError</m:ResponseCode>
          <m:DelegateUser>
            <t:UserId>
              <t:SID>S-1-5-21-1337771579-694202782-848329751-1535264</t:SID>
              <t:PrimarySmtpAddress>contactdelegate@contoso.com</t:PrimarySmtpAddress>
              <t:DisplayName>contactdelegate</t:DisplayName>
            </t:UserId>
            <t:ReceiveCopiesOfMeetingMessages>false</t:ReceiveCopiesOfMeetingMessages>
            <t:ViewPrivateItems>false</t:ViewPrivateItems>
          </m:DelegateUser>
        </m:DelegateUserResponseMessageType>
        <m:DelegateUserResponseMessageType ResponseClass="Success">
          <m:ResponseCode>NoError</m:ResponseCode>
          <m:DelegateUser>
            <t:UserId>
              <t:SID>S-1-5-21-1337771579-694202782-848329751-1535223</t:SID>
              <t:PrimarySmtpAddress>emaildelegate@contoso.com</t:PrimarySmtpAddress>
              <t:DisplayName>emaildelegate</t:DisplayName>
            </t:UserId>
            <t:ReceiveCopiesOfMeetingMessages>false</t:ReceiveCopiesOfMeetingMessages>
            <t:ViewPrivateItems>false</t:ViewPrivateItems>
          </m:DelegateUser>
        </m:DelegateUserResponseMessageType>
      </m:ResponseMessages>
    </m:AddDelegateResponse>
  </s:Body>
</s:Envelope>

Remover representantes usando a API gerenciada do EWSRemove delegates by using the EWS Managed API

Você pode remover representantes de uma caixa de correio de destino usando o método de API gerenciada do EWS ExchangeService. RemoveDelegates .You can remove delegates from a target mailbox by using the ExchangeService.RemoveDelegates EWS Managed API method. Neste exemplo, as permissões de representante definidas no exemplo de adicionar um representante serão removidas.In this example, the delegate permissions set in the add a delegate example are removed.

Este exemplo pressupõe que o serviço é um objeto ExchangeService válido para o proprietário da caixa de correio e que o usuário foi autenticado em um servidor Exchange.This example assumes that service is a valid ExchangeService object for the mailbox owner, and that the user has been authenticated to an Exchange server.

public static Collection<DelegateUserResponse> RemoveDelegates(ExchangeService service)
{
    // Create a list to hold the delegates to delete.
    List<UserId> deletedDelegates = new System.Collections.Generic.List<UserId>();
    // Add the delegate to the list of new delegates.
    deletedDelegates.Add("calendardelegate@contoso.com");
    // Add the delegate to the list of new delegates.
    deletedDelegates.Add("contactdelegate@contoso.com");
    // Add the delegate to the list of new delegates.
    deletedDelegates.Add("emaildelegate@contoso.com");
    // Create a mailbox object that represents the mailbox owner.
    Mailbox mailbox = new Mailbox("primary@contoso.com");
    // Call the AddDelegates method to add the delegates to the target mailbox.
    Collection<DelegateUserResponse> response = service.RemoveDelegates(mailbox, deletedDelegates);
    foreach (DelegateUserResponse resp in response)
    {
        // Print out the result and the last eight characters of the item ID.
        Console.WriteLine("Result: {0}", resp.Result);
        Console.WriteLine("Error Code: {0}", resp.ErrorCode);
        Console.WriteLine("ErrorMessage: {0}\r\n", resp.ErrorMessage);
    }
    return response;
}

Remover representantes usando EWSRemove delegates by using EWS

Você pode remover representantes de uma caixa de correio usando a operação RemoveDelegate do EWS.You can remove delegates from a mailbox by using the RemoveDelegate EWS operation. Neste exemplo, as permissões de representante definidas no exemplo de adicionar um representante serão removidas.In this example, the delegate permissions set in the add a delegate example are removed.

Essa é também a solicitação XML que a API gerenciada do EWS envia quando você usa o método RemoveDelegates para remover representantes.This is also the XML request that the EWS Managed API sends when you use the RemoveDelegates method to remove delegates.

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xmlns:m="https://schemas.microsoft.com/exchange/services/2006/messages"
               xmlns:t="https://schemas.microsoft.com/exchange/services/2006/types"
               xmlns:soap="https://schemas.xmlsoap.org/soap/envelope/">
  <soap:Header>
    <t:RequestServerVersion Version="Exchange2007_SP1" />
  </soap:Header>
  <soap:Body>
    <m:RemoveDelegate>
      <m:Mailbox>
        <t:EmailAddress>primary@contoso.com</t:EmailAddress>
      </m:Mailbox>
      <m:UserIds>
        <t:UserId>
          <t:PrimarySmtpAddress>calendardelegate@contoso.com</t:PrimarySmtpAddress>
        </t:UserId>
        <t:UserId>
          <t:PrimarySmtpAddress>contactdelegate@contoso.com</t:PrimarySmtpAddress>
        </t:UserId>
        <t:UserId>
          <t:PrimarySmtpAddress>emaildelegate@contoso.com</t:PrimarySmtpAddress>
        </t:UserId>
      </m:UserIds>
    </m:RemoveDelegate>
  </soap:Body>
</soap:Envelope>

O servidor responde à solicitação RemoveDelegate com uma mensagem AddDelegateResponse que inclui um valor de elemento ResponseCode de NOERROR, que indica que os representantes foram removidos com êxito.The server responds to the RemoveDelegate request with a AddDelegateResponse message that includes a ResponseCode element value of NoError, which indicates that the delegates were successfully removed.

Próximas etapasNext steps

Após adicionar representantes às pastas de calendário, email e tarefas, o representante pode acessar os itens nas pastas.After you add delegates to calendar, email, and task folders, the delegate can access the items in the folders. Para saber mais, confira os seguintes artigos:To learn more, see the following articles:

Se as pastas para as quais você adicionou representantes incluírem pastas filhas que foram criadas antes de você conceder acesso de representante, o representante não poderá acessar essas pastas sem permissões adicionais.If the folders for which you added delegates include child folders that were created before you granted the delegate access, the delegate will not be able to access those folders without additional permissions. Para adicionar essas permissões ou modificar permissões para qualquer outra pasta, confira definir permissões de pasta para outro usuário usando o EWS no Exchange.To add these permissions, or modify permissions for any other folders, see Set folder permissions for another user by using EWS in Exchange.

Confira tambémSee also