Delete E-mail Attachments with Plugin in Dynamics CRM 2011

Paul Nieuwelaar, 28 August 2012

Recently I had a requirement where I needed to delete e-mail attachments from certain e-mail messages delivered by the e-mail router. The idea was that if an e-mail was deemed ‘confidential’, its attachments would be stripped from the e-mail so users would not be able to see what the attachments were.

 Delete Email Attachments with Plugin in Dynamics CRM 2011

To do this, we first need to get the logic for the plugin. Assuming we have the ID/Guid of the CRM e-mail message, we can do a retrieve on E-Mail Attachments to find all the attachments linked to the specified E-mail Message.

To find the Entity Schema name of the E-Mail Attachments entity, we can check the Customizations area.

 Delete Email Attachments with Plugin in Dynamics CRM 2011

As you can see, the entity we need to retrieve is ‘activitymimeattachment’.

Next we need to find the attribute that links the E-Mail Attachment to the E-mail Message. If we check the Fields on the E-Mail Attachment entity, we can see a field ‘activityid’. This field contains the ID of our E-mail, so we can use this to find only attachments for a specific e-mail.

 Delete Email Attachments with Plugin in Dynamics CRM 2011

Using the Method below, we can pass in our E-mail ID, and the related E-Mail Attachments will be retrieved, and then deleted. Notice that we are retrieving the ‘activitymimeattachment’ entity, and filtering where the ‘activityid’ equals our specified e-mail.

private void DeleteEmailAttachments(Guid emailId)
{
    //retrieve the related attachments for the e-mail
    QueryExpression query = new QueryExpression { EntityName = "activitymimeattachment" };
    query.Criteria.AddCondition("activityid", ConditionOperator.Equal, emailId);
    query.ColumnSet = new ColumnSet("activitymimeattachmentid");
    EntityCollection collection = _sdk.RetrieveMultiple(query);

    //if one or more attachments exist, delete them
    if (collection.Entities.Count > 0)
    {
        collection.Entities.ToList().ForEach(a =>
        {
            _sdk.Delete("activitymimeattachment", a.Id);
        });
    }
}

Finally we need to register our plugin. We can use the ‘DeliverIncoming’ plugin message, which will fire every time an e-mail comes in from the e-mail router.

After the plugin has run on a new e-mail, we can see that all attachments have been deleted.

Delete Email Attachments with Plugin in Dynamics CRM 2011