web
You’re offline. This is a read only version of the page.
close
Skip to main content
Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

CRM 2016 eMail Attachment

(0) ShareShare
ReportReport
Posted on by 247

I have spent 2 weeks trying to attach a PDF to an email with no success.  I know I am missing something very simple but cannot find a solution. I've tried every solution i could google no success.

Step 1 Generate the PDF from HTML - Completed

Step 2 Read/Retrieve the PDF - Completed

   var pdflocation = pdfpath + printContents + '.pdf';
    jQuery.get(pdflocation, function(data) {
            var str = base64ToArrayBuffer(data);
            console.log(btoa(str));
    });

Step 3 convert to bytearry - Fail - Fail - Fail

         function base64ToArrayBuffer(data) {  
/*
            var reader = new FileReader();
            reader.readAsArrayBuffer(data);
            var arrayBuffer = reader.result
            var bytes = new Uint8Array(arrayBuffer);
    
            //var buffer =  atob(data);
            var buffer = new ArrayBuffer( data.length );
            //var buffer = window.btoa(escape(encodeURIComponent( data )));
            //var buffer = encodeURIComponent( data );
            var len = buffer.length;
            var bytes = new Uint8Array( len );
*/
              
            var buffer = new ArrayBuffer( data.length ), // res is this.response in your case
                bytes   = new Uint8Array( buffer ),
                len    = bytes.length,
                fromCharCode = String.fromCharCode,
                i, s, str;    
            str = "";


                 for ( i = len; i--; ) {
                   bytes[i] = data[i].charCodeAt(0);
                 }

                 for ( i = 0; i < len; ++i ) {
                   str += fromCharCode( bytes[i] );
                 }    
/*
*/
/*

                 for ( i = 0; i < len; ++i ) {
                   //str += fromCharCode( data[i].charCodeAt(0) & 0xff );
                   bytes[i] += buffer.charCodeAt(i);
                 }
*/                 
            //for (var i = 0; i < len; i++)        {
              //  bytes[i] = buffer.charCodeAt(i);
            //}

            return bytes.buffer;
        }

Any and all help would be appreciated.

*This post is locked for comments

I have the same question (0)
  • Suggested answer
    ram r Profile Picture
    on at
    RE: CRM 2016 eMail Attachment

    Try this,

    function _arrayBufferToBase64(buffer) { // Convert Array Buffer to Base 64 string

    var binary = '';

    var bytes = new Uint8Array(buffer);

    var len = bytes.byteLength;

    for (var i = 0; i < len; i++) {

    binary += String.fromCharCode(bytes[i]);

    }

    return window.btoa(binary);

    }

    Below is the reference

    scaleablesolutions.com/upload-notes-attachments-using-javascript-and-rest

  • IwishIknow Profile Picture
    247 on at
    RE: CRM 2016 eMail Attachment

    Getting error for "var bytes = new Uint8Array(buffer);"

    Typed array constructor argument is invalid

  • ram r Profile Picture
    on at
    RE: CRM 2016 eMail Attachment

    which browser are you using, there is an issue with IE 10 it seems, workaround is as follows

    stackoverflow.com/.../array-buffer-ie10-typed-array-constructor-argument-is-invalid

  • IwishIknow Profile Picture
    247 on at
    RE: CRM 2016 eMail Attachment

    I get no error but the pdf attachment will not open - I get a load error.

  • ram r Profile Picture
    on at
    RE: CRM 2016 eMail Attachment

    can you share the updated code?

  • IwishIknow Profile Picture
    247 on at
    RE: CRM 2016 eMail Attachment

    I attempted 2 ways in chrome and IE

    function _arrayBufferToBase64(buffer) { // Convert Array Buffer to Base 64 string

    var binary = '';

    //var bytes = new Uint8Array(buffer);

    var bytes = new Uint32Array(buffer);

    var len = bytes.byteLength;

    for (var i = 0; i < len; i++) {

    binary += String.fromCharCode(bytes[i]);

    }

    return window.btoa(binary);

    }        

           function CreateEmailAttachment(results) {            

              var aFileParts = [document.documentElement.innerHTML];

              var oMyBlob = new Blob([newDoc]); // the blob

              //Email attachment parameters

              var activitymimeattachment = Object();

              activitymimeattachment.ObjectId = Object();

              activitymimeattachment.ObjectId.LogicalName = "email";

              activitymimeattachment.ObjectId.Id = results.ActivityId;

              activitymimeattachment.ObjectTypeCode = "email",

              activitymimeattachment.Subject = "File Attachment";

                 var pdflocation = pdfpath + printContents + '.pdf';

    /* get file using ajax both binary  and string              

              $.ajax({

                url: pdflocation,

                type: "GET",

                //dataType: "binary",

                dataType: "string",

                processData: false,

                success: function(result){

                    var buffer = new ArrayBuffer( result.length );

                    var len = buffer.length;

                    var bytes = new Uint8Array( buffer );

                    for (var i = 0; i < len; i++)        {

                      bytes[i] = buffer.charCodeAt(i);

                    }

                    var str = _arrayBufferToBase64(result)

               // do something with binary data

                    activitymimeattachment.Body =  str;

                    activitymimeattachment.FileName = OrderNum + ".pdf";

                    activitymimeattachment.MimeType = "application/pdf";

                    //Attachment call

                    SDK.REST.createRecord(activitymimeattachment, "ActivityMimeAttachment", ActivityMimeAttachmentCallBack, function (error) { errorHandler(error, options + "- [CreateEmailAttachment]"); });

                },

                error: function() { alert('Failed!'); }

              });

    */

    /* jQuery

                 jQuery.get(pdflocation, function(data) {

                    var str = _arrayBufferToBase64(data);

                    //var str = new Blob([data], { type: 'application/pdf' });

                    //activitymimeattachment.Body =  btoa(encode64(BinaryToArray(str)));

                    //activitymimeattachment.Body =  data;

                    //activitymimeattachment.Body =  btoa(unescape(str));

                    //activitymimeattachment.Body =  atob(unescape(str));

                    activitymimeattachment.Body =  str;

                    activitymimeattachment.FileName = OrderNum + ".pdf";

                    activitymimeattachment.MimeType = "application/pdf";

                    //Attachment call

                    SDK.REST.createRecord(activitymimeattachment, "ActivityMimeAttachment", ActivityMimeAttachmentCallBack, function (error) { errorHandler(error, options + "- [CreateEmailAttachment]"); });

                 });

    */

           }

    Just remove the comment for each section

  • Suggested answer
    ram r Profile Picture
    on at
    RE: CRM 2016 eMail Attachment

    Get the base64 output and try to test in some online tester such as

    www.motobit.com/.../base64-decoder-encoder.asp

    The following code works accross almost all browsers for me

       var selectedFile = document.getElementById("inputFile").files;

       //Check File is not Empty

       if (selectedFile.length > 0) {

           // Select the very first file from list

           var fileToLoad = selectedFile[0];

           // FileReader function for read the file.

           var fileReader = new FileReader();

           var base64;

           // Onload of file read the file content

           fileReader.onload = function (fileLoadedEvent) {

               base64 = fileLoadedEvent.target.result;

               // Print data in console

               console.log(base64);

           }

  • Suggested answer
    Nithya Gopinath Profile Picture
    17,078 on at
    RE: CRM 2016 eMail Attachment

    Hi,

    Just replace the code below and see if it works.

     function base64ToArrayBuffer(data) {
        var binary_string =  window.atob(data);
        var len = binary_string.length;
        var bytes = new Uint8Array( len );
        for (var i = 0; i < len; i++)        {
            bytes[i] = binary_string.charCodeAt(i);
        }
        return bytes.buffer;
    }

    Hope this helps.

  • IwishIknow Profile Picture
    247 on at
    RE: CRM 2016 eMail Attachment

    This returns and error SCRIPT5022: InvalidCharacterError IE

    Chrome error - Uncaught DOMException: Failed to execute 'atob' on 'Window': The string

  • Suggested answer
    Nithya Gopinath Profile Picture
    17,078 on at
    RE: CRM 2016 eMail Attachment

    Please replace the line as follows.

    var binary_string =  atob(data);

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Abhilash Warrier – Community Spotlight

We are honored to recognize Abhilash Warrier as our Community Spotlight honoree for…

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
HR-09070029-0 Profile Picture

HR-09070029-0 2

#2
ED-30091530-0 Profile Picture

ED-30091530-0 1

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans