The other day I had a request from a client to create a customer ASPX webpage that sends emails through CRM along with the attached Excel file. Here is an example of how this can be completed. Start with the Send Email sample code from Microsoft website located here and added the functionality of attaching files to the email.


Adding an attached file to the Email


Step 1) First you need to attach a file to the ActivityMimeAttachment as base64



public ActivityMimeAttachment AttachFileToEmail(String fileName)


// Open a file and read its contents into a byte array.

var fileLocation    = ConfigurationManager.AppSettings["ExcelPath"] + fileName;

var stream          = File.OpenRead(fileLocation);

var byteData        = new byte[stream.Length];


stream.Read(byteData, 0, byteData.Length);


// Encode the data using base64.

var encodedData = Convert.ToBase64String(byteData);

var extension = Path.GetExtension(fileLocation).ToLower();


String mimeType = null;


switch (extension)


case ".xls":

mimeType = "application/";


case ".xlsx":

mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";




var sampleAttachment = new ActivityMimeAttachment


ObjectId        = new EntityReference(Email.EntityLogicalName, _emailId),

ObjectTypeCode  = Email.EntityLogicalName,

FileName        = fileName,

MimeType        = mimeType,

Body            = encodedData,



return sampleAttachment;



Step 2) Add the EncodedDate to the Create an e-mail message in the Sample Code


// Create an e-mail message.

Email email = new Email


To = new ActivityParty[] { toParty },

From = new ActivityParty[] { fromParty },

Subject = "SDK Sample e-mail",

Description = "CRM SDK Sample Body

DirectionCode = true,

email_activity_mime_attachment = new[] { AttachFileToEmail("FileName") }



The Sample of the Closed Activity Record in CRM


You can download my SendEmail sample code here.


If you have any questions or need help please contact me @ steven.jennings[at]