Excluir anexos usando EWS no ExchangeDelete attachments by using EWS in Exchange

Saiba como excluir anexos de itens usando a API gerenciada do EWS ou o EWS no Exchange.Learn how to delete attachments from items by using the EWS Managed API or EWS in Exchange.

Você tem várias opções quando se trata de excluir anexos de arquivo e de item de itens usando a API gerenciada do EWS.You have a number of options when it comes to deleting file and item attachments from items by using the EWS Managed API. Você pode excluir todos os anexos da mensagem, excluir por um nome de arquivo ou excluir por posição na coleção.You can delete all the attachments from the message, delete by a file name, or delete by position in the collection. Para cada uma dessas opções, há um método AttachmentCollection .For each of these options, there is an AttachmentCollection method.

Por outro lado, com o EWS, não importa se você está excluindo todos os anexos de um item ou apenas um, a sequência de operações é a mesma.Conversely, with EWS, no matter whether you're deleting all attachments from an item or just one, the sequence of operations is same. Diferentemente da API gerenciada por EWS, o EWS não inclui operações separadas para excluir com base no nome ou na posição na matriz Attachments.Unlike the EWS Managed API, EWS does not include separate operations to delete based on name or position in the attachments array.

Tabela 1. Métodos da API gerenciada do EWS e operações do EWS para exclusão de anexosTable 1. EWS Managed API methods and EWS operations for deleting attachments

TarefaTask Método de API gerenciada do EWSEWS Managed API method Operação do EWSEWS operation
Excluir todos os anexos de um item.Delete all attachments from an item.
Item. bind, seguido por AttachmentCollection. Clear, seguido por EmailMessage. UpdateItem.Bind, followed by AttachmentCollection.Clear, followed by EmailMessage.Update
GetItem seguido por DeleteAttachmentGetItem followed by DeleteAttachment
Excluir um anexo de um item pelo nome.Delete an attachment from an item by name.
Item. bind, seguido por AttachmentCollection. Remove, seguido por EmailMessage. UpdateItem.Bind, followed by AttachmentCollection.Remove, followed by EmailMessage.Update
GetItem seguido por DeleteAttachmentGetItem followed by DeleteAttachment
Excluir um anexo de um item pela posição na coleção.Delete an attachment from an item by position in the collection.
Item. bind, seguido por AttachmentCollection. RemoveAt, seguido por EmailMessage. UpdateItem.Bind, followed by AttachmentCollection.RemoveAt, followed by EmailMessage.Update
GetItem seguido por DeleteAttachmentGetItem followed by DeleteAttachment

Excluir todos os anexos de um email usando a API gerenciada do EWSDelete all attachments from an email by using the EWS Managed API

O exemplo de código a seguir mostra como excluir todos os anexos de um email por:The following code example shows how to delete all attachments from an email by:

  1. Usando o método EmailMessage. bind para vincular a uma mensagem de email existente e recuperar a coleção de anexos.Using the EmailMessage.Bind method to bind to an existing email message and retrieve the collection of Attachments.

  2. Usando o método AttachmentCollection. Clear para excluir todos os anexos do email.Using the AttachmentCollection.Clear method to delete all the attachments from the email.

  3. Usando o método EmailMessage. Update para salvar as alterações.Using the EmailMessage.Update method to save the changes.

Este exemplo pressupõe que o serviço é um objeto ExchangeService válido, ItemId é o ItemId da mensagem a partir da qual os anexos serão excluídos e que o usuário foi autenticado em um servidor Exchange.This example assumes that service is a valid ExchangeService object, itemId is the ItemId of the message from which attachments will be deleted, and that the user has been authenticated to an Exchange server.

public static void DeleteAllAttachments(ExchangeService service, ItemId itemId)
{
    // Bind to an existing message by using its item ID and requesting its attachments collection.
    // This method results in a GetItem call to EWS.
    EmailMessage message = EmailMessage.Bind(service, itemId, new PropertySet(ItemSchema.Attachments));
    // Delete all attachments from the message.
    message.Attachments.Clear();
    // Save the updated message.
    // This method results in an DeleteAttachment call to EWS.
    message.Update(ConflictResolutionMode.AlwaysOverwrite);
}

Excluir um anexo por nome de um email usando a API gerenciada do EWSDelete an attachment by name from an email by using the EWS Managed API

O exemplo de código a seguir mostra como excluir um anexo por nome:The following code example shows how delete an attachment by name by:

  1. Usando o método EmailMessage. bind para vincular a uma mensagem de email existente e recuperar a coleção de anexos.Using the EmailMessage.Bind method to bind to an existing email message and retrieve the collection of Attachments.

  2. Usando o método AttachmentCollection. Remove para excluir um anexo chamado fileattachment. txt.Using the AttachmentCollection.Remove method to delete an attachment named FileAttachment.txt.

  3. Usando o método EmailMessage. Update para salvar as alterações.Using the EmailMessage.Update method to save the changes.

Este exemplo pressupõe que o serviço é um objeto ExchangeService válido, ItemId é o ItemId da mensagem a partir da qual o anexo será excluído e que o usuário foi autenticado em um servidor Exchange.This example assumes that service is a valid ExchangeService object, itemId is the ItemId of the message from which the attachment will be deleted, and that the user has been authenticated to an Exchange server.

public static void DeleteNamedAttachments(ExchangeService service, ItemId itemId)
{
    // Bind to an existing message by using its item ID and requesting its attachments collection.
    // This method results in a GetItem call to EWS.
    EmailMessage message = EmailMessage.Bind(service, itemId, new PropertySet(ItemSchema.Attachments));
    // Iterate through the attachments collection and delete the attachment named "FileAttachment.txt," if it exists.
    foreach (Attachment attachment in message.Attachments)
    {
        if (attachment.Name == "FileAttachment.txt")
        {
            message.Attachments.Remove(attachment);
            break;
        }
    }
    // Save the updated message.
    // This method results in an DeleteAttachment call to EWS.
    message.Update(ConflictResolutionMode.AlwaysOverwrite);
}

Excluir anexos por posição usando a API gerenciada do EWSDelete attachments by position by using the EWS Managed API

O exemplo de código a seguir mostra como excluir um anexo por posição por:The following code example shows how to delete an attachment by position by:

  1. Usando o método EmailMessage. bind para associar a uma mensagem de email existente e recuperar a coleção de anexos e a propriedade EmailMessage. HasAttachments .Using the EmailMessage.Bind method to bind to an existing email message and retrieve the collection of Attachments and the EmailMessage.HasAttachments property.

  2. Usando o método AttachmentCollection. Remove para excluir o primeiro anexo na coleção.Using the AttachmentCollection.Remove method to delete the first attachment in the collection.

  3. Usando o método EmailMessage. Update para salvar as alterações.Using the EmailMessage.Update method to save the changes.

Este exemplo pressupõe que o serviço é um objeto ExchangeService válido, ItemId é o ItemId da mensagem a partir da qual o anexo será excluído e que o usuário foi autenticado em um servidor Exchange.This example assumes that service is a valid ExchangeService object, itemId is the ItemId of the message from which the attachment will be deleted, and that the user has been authenticated to an Exchange server.

public static void DeleteAttachmentByPosition(ExchangeService service, ItemId itemId)
{
    // Bind to an existing message by using its item ID and requesting the HasAttachments property and the attachments collection.
    // This method results in a GetItem call to EWS.
    EmailMessage message = EmailMessage.Bind(service, itemId, new PropertySet(EmailMessageSchema.HasAttachments, ItemSchema.Attachments));
    // Remove attachments using the zero-based index position of the attachment in the attachments collection.
    if (message.HasAttachments)
    {
        message.Attachments.RemoveAt(0);
    }
    // Save the updated message.
    // This method results in an DeleteAttachment call to EWS.
    message.Update(ConflictResolutionMode.AlwaysOverwrite);
}

Excluir anexos de um item usando o EWSDelete attachments from an item by using EWS

Para excluir anexos usando o EWS, primeiro você precisa recuperar a mensagem e a coleção Attachment para determinar o attachmentid (GetAttachment e DeleteAttachment) do anexo a ser excluído.To delete attachments by using EWS, you first need to retrieve the message and the attachment collection to determine the AttachmentId (GetAttachment and DeleteAttachment) of the attachment to delete. Após ter um ou mais valores attachmentid para excluir, chame a operação DeleteAttachment para remover os anexos especificados da mensagem.After you have one or more AttachmentId values to delete, call the DeleteAttachment operation to remove the specified attachments from the message.

O exemplo de código a seguir mostra como usar a operação GetItem para obter uma mensagem de email e a coleção de anexos na mensagem.The following code example shows how to use the GetItem operation to get an email message and the collection of attachments on the message. Essa é também a primeira solicitação XML que a API gerenciada do EWS envia quando você usa a API gerenciada do EWS para excluir todos os anexos de um email.This is also the first XML request that the EWS Managed API sends when you use the EWS Managed API to delete all attachments from an email. Os valores de alguns atributos são reduzidos para facilitar a leitura.The values of some attributes are shortened for readability.

<?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" />
    <t:TimeZoneContext>
      <t:TimeZoneDefinition Id="Central Standard Time" />
    </t:TimeZoneContext>
  </soap:Header>
  <soap:Body>
    <m:GetItem>
      <m:ItemShape>
        <t:BaseShape>IdOnly</t:BaseShape>
        <t:AdditionalProperties>
          <t:FieldURI FieldURI="item:Attachments" />
        </t:AdditionalProperties>
      </m:ItemShape>
      <m:ItemIds>
        <t:ItemId Id="uqE1AAA=" />
      </m:ItemIds>
    </m:GetItem>
  </soap:Body>
</soap:Envelope>

O servidor responde à solicitação GetItem com uma mensagem GetItemResponse que inclui um valor de ResponseCode de NOERROR, que indica que o email foi recuperado com êxito e os valores attachmentid dos anexos existentes.The server responds to the GetItem request with a GetItemResponse message that includes a ResponseCode value of NoError, which indicates that the email was retrieved successfully, and the AttachmentId values of the existing attachments.

<?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="939"
                         MinorBuildNumber="12"
                         Version="V2_11"
                         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:GetItemResponse xmlns:m="https://schemas.microsoft.com/exchange/services/2006/messages"
                       xmlns:t="https://schemas.microsoft.com/exchange/services/2006/types">
      <m:ResponseMessages>
        <m:GetItemResponseMessage ResponseClass="Success">
          <m:ResponseCode>NoError</m:ResponseCode>
          <m:Items>
            <t:Message>
              <t:ItemId Id="uqE1AAA="
                        ChangeKey="CQAAABYAAAAFI5DJmZv+TLtyLOLIF1S5AAAXulcd" />
              <t:Attachments>
                <t:FileAttachment>
                  <t:AttachmentId Id="IpHLObE=" />
                  <t:Name>FileAttachment.txt</t:Name>
                </t:FileAttachment>
                <t:FileAttachment>
                  <t:AttachmentId Id="QuHSSmY=" />
                  <t:Name>SecondAttachment.txt</t:Name>
                </t:FileAttachment>
                <t:FileAttachment>
                  <t:AttachmentId Id="qf2KoPo=" />
                  <t:Name>ThirdAttachment.jpg</t:Name>
                </t:FileAttachment>
                <t:FileAttachment>
                  <t:AttachmentId Id="NFQMnMc=" />
                  <t:Name>FourthAttachment.txt</t:Name>
                </t:FileAttachment>
                <t:ItemAttachment>
                  <t:AttachmentId Id="jJvbLXQ=" />
                  <t:Name>Attached Message Item</t:Name>
                </t:ItemAttachment>
              </t:Attachments>
            </t:Message>
          </m:Items>
        </m:GetItemResponseMessage>
      </m:ResponseMessages>
    </m:GetItemResponse>
  </s:Body>
</s:Envelope>

Depois de determinar qual anexo excluir, chame a operação DeleteAttachment e inclua os valores attachmentid dos anexos a serem excluídos.After you determine which attachment to delete, call the DeleteAttachment operation and include the AttachmentId values of the attachments to delete.

<?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" />
    <t:TimeZoneContext>
      <t:TimeZoneDefinition Id="Central Standard Time" />
    </t:TimeZoneContext>
  </soap:Header>
  <soap:Body>
    <m:DeleteAttachment>
      <m:AttachmentIds>
        <t:AttachmentId Id="IpHLObE=" />
        <t:AttachmentId Id="QuHSSmY=" />
        <t:AttachmentId Id="qf2KoPo=" />
        <t:AttachmentId Id="NFQMnMc=" />
        <t:AttachmentId Id="jJvbLXQ=" />
      </m:AttachmentIds>
    </m:DeleteAttachment>
  </soap:Body>
</soap:Envelope>

O servidor responde à solicitação DeleteAttachment com uma mensagem DeleteAttachmentResponse que inclui um valor de ResponseCode de NOERROR para cada DeleteAttachmentResponseMessage, o que indica que cada anexo foi excluído com êxito. Os valores de alguns atributos são reduzidos para facilitar a leitura.The values of some attributes are shortened for readability.

<?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="939"
                         MinorBuildNumber="12"
                         Version="V2_11"
                         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:DeleteAttachmentResponse xmlns:m="https://schemas.microsoft.com/exchange/services/2006/messages"
                                xmlns:t="https://schemas.microsoft.com/exchange/services/2006/types">
      <m:ResponseMessages>
        <m:DeleteAttachmentResponseMessage ResponseClass="Success">
          <m:ResponseCode>NoError</m:ResponseCode>
          <m:RootItemId RootItemId="uqE1AAA=" RootItemChangeKey="AAAXulck" />
        </m:DeleteAttachmentResponseMessage>
        <m:DeleteAttachmentResponseMessage ResponseClass="Success">
          <m:ResponseCode>NoError</m:ResponseCode>
          <m:RootItemId RootItemId="uqE1AAA=" RootItemChangeKey="AAAXulck" />
        </m:DeleteAttachmentResponseMessage>
        <m:DeleteAttachmentResponseMessage ResponseClass="Success">
          <m:ResponseCode>NoError</m:ResponseCode>
          <m:RootItemId RootItemId="uqE1AAA=" RootItemChangeKey="AAAXulck" />
        </m:DeleteAttachmentResponseMessage>
        <m:DeleteAttachmentResponseMessage ResponseClass="Success">
          <m:ResponseCode>NoError</m:ResponseCode>
          <m:RootItemId RootItemId="uqE1AAA=" RootItemChangeKey="AAAXulck" />
        </m:DeleteAttachmentResponseMessage>
        <m:DeleteAttachmentResponseMessage ResponseClass="Success">
          <m:ResponseCode>NoError</m:ResponseCode>
          <m:RootItemId RootItemId="uqE1AAA=" RootItemChangeKey="AAAXulck" />
        </m:DeleteAttachmentResponseMessage>
      </m:ResponseMessages>
    </m:DeleteAttachmentResponse>
  </s:Body>
</s:Envelope>

Confira tambémSee also