MSCRM database on a diet! – Stripping emails

Gayan Perera, 27 September 2010

MSCRM database on a diet! – Stripping emails 

When emails are tracked in Dynamics CRM automatically or manually via the ‘Track in CRM’ button if the email contains attachments they’ll get stored in the Dynamics CRM database. Over a period of time your database will grow quite quickly.

Dynamics CRM is flexible enough that we can route these attachments elsewhere via plugins.

The above screenshot shows an email which was tracked in Dynamics CRM and sent to two recipients with an attachment. When this email was tracked in Dynamics CRM, a plugin intercepted and stripped the attachment, stored it inside the file system, removed the content from CRM (hence the 0 in the “File Size (Bytes)” column).

The plugin goes a step further; it attaches the attachment(s) against the clients’ domain name. For example, if an email comes into one of your staff members’ inbox, it tracks the attachments against the person sending the email. If one of your staff members sends an email out it stores against the recipient. This allows you to keep all attachments against a customer in a single location without bloating Dynamics CRM.

How it’s done

The plugin hooks into the DeliverPromote and DeliverIncoming messages asynchronously. It then grabs the EmailId from the OutputParameters property of the plugin execution context.

MSCRM database on a diet! – Stripping emails

Attachment body is stored in a Base64 string in Dynamics CRM. To decode an attachment use the following piece of code.

Convert.FromBase64String(attachment.body)

Once you’ve saved the file to the file system, Sharepoint, cloud storage or any other location, you can strip the content by setting the attachment body to nothing.

crm.Update<ActivityAttachment>(new ActivityAttachment
{
    ActivityMimeAttachmentId = attachmentId,
    Body = ""
});

Storage locations can be set via Dynamics CRM using a configuration entity.

MSCRM database on a diet! – Stripping emails

To determine the domain name we use the DirectionCode of the email, if it’s set to true it means the email is an outgoing email; in this case the domain name will be coming from the To field. If it’s set to false it means the emails is an incoming email; in this case the domain name will be coming from the Form field.

To allow users to download the attachments create a custom aspx page and embed it inside the email activity. Keep an eye out for that example…