Send a PDF File as an Attachment in Mail using JavaScript in CRM 2015/2016

Today I will show how to "Send a PDF File as an attachment in Mail using java script in CRM 2015/2016. " To work around this we need to follow some steps:

Step 1:
Create a record in "Email" Entity with some subject value.

Step 2: Create a record for activityParty in "ActivityParty" Entity.

Step 3: Add the attachement of pdf in base64 to ActivityMimeAttachment and create a record in "ActivityMimeAttachment" Entity.

Step 4: Open the Email form based on the newly created activityId.
  1. CreateEmail: function()  
  2. {  
  3.         var email = new Object();  
  4.   
  5.         email.Subject = "Testing the sending of mail through java script";  
  6.   
  7.         SDK.REST.createRecord(email, "Email", EmailCallBack, function(error)  
  8.          {  
  9.             alert(error.message);  
  10.         });  
  11.   
  12.     },  
  13.     When the Email record is created with sucessfull, Then we have to create activity party  
  14. for that email.  
  15.     // Email Call Back function  
  16. EmailCallBack: function(result)  
  17. {  
  18.     email1 = result;  
  19.     var activityParty = new Object();  
  20.     // Set the "party" of the ActivityParty // EntityReference of an entity this activityparty relatated to.   
  21.     activityParty.PartyId = {  
  22.         Id: Xrm.Page.context.getUserId(), // id of the the current user which becomes the sender  
  23.         LogicalName: "systemuser"  
  24.     };  
  25.     // Set the "activity" of the ActivityParty  
  26.     // EntityReference.  
  27.     activityParty.ActivityId =  
  28.     {  
  29.         Id: result.ActivityId,  
  30.         LogicalName: "email"  
  31.     };  
  32.     // Set the participation type (what role the party has on the activity).  
  33.     activityParty.ParticipationTypeMask =  
  34.     {  
  35.         Value: 1  
  36.     }; // 1 mean Sender  
  37.   
  38.     SDK.REST.createRecord(activityParty, "ActivityParty", ActivityPartyCallBack, function(error) {  
  39.         alert(error.message);  
  40.     });  
  41. },  
When activity Party is created we need to attached a pdf file as base64 to the mail. For more information on how to create a pdf file follow my blog.
  1. ActivityPartyCallBack: function(result2)  
  2. {  
  3.         // Generate the pdf file to attached to the Email.  
  4.         var responseSession = getReportingSession();  
  5.         encodePdf(responseSession);  
  6.     },  
  7.   
  8.     // create a Email record with the attachement and other parameters.  
  9.     CreateEmailAttachment: function(bdy)  
  10. {  
  11.   
  12.         //Email attachment parameters  
  13.         var activitymimeattachment = Object();  
  14.         activitymimeattachment.ObjectId = Object();  
  15.         activitymimeattachment.ObjectId.LogicalName = "email";  
  16.         activitymimeattachment.ObjectId.Id = email1.ActivityId;  
  17.         activitymimeattachment.ObjectTypeCode = "email",  
  18.             activitymimeattachment.Subject = "File Attachment";  
  19.         activitymimeattachment.Body = bdy;  
  20.         activitymimeattachment.FileName = "xyz.pdf";  
  21.         //Attachment call  
  22.         activitymimeattachment.MimeType = "application/pdf";  
  23.   
  24.         SDK.REST.createRecord(activitymimeattachment, "ActivityMimeAttachment", ActivityMimeAttachmentCallBack, function(error)   
  25.         {  
  26.             alert(error.message);  
  27.         });  
  28.   
  29.     },  
  30.     ActivityMimeAttachmentCallBack: function(result)   
  31. {  
  32.         var options =   
  33.         {  
  34.             openInNewWindow: true  
  35.         };  
  36.         Xrm.Utility.openEntityForm("email", email1.ActivityId, null, options);  
  37.   
  38.     },  
  39.   
  40.     //Encode the binary output pdf file to create an attachement  
  41.     encodePdf: function(responseSession)  
  42. {  
  43.   
  44.         var retrieveEntityReq = new XMLHttpRequest();  
  45.   
  46.         var pth = Xrm.Page.context.getClientUrl() + "/Reserved.ReportViewerWebControl.axd?ReportSession=" + responseSession[0] + "&Culture=1033&CultureOverrides=True&UICulture=1033&UICultureOverrides=True&ReportStack=1&ControlID=" + responseSession[1] + "&OpType=Export&FileName=Public&ContentDisposition=OnlyHtmlInline&Format=PDF";  
  47.   
  48.         retrieveEntityReq.open("GET", pth, true);  
  49.         retrieveEntityReq.setRequestHeader("Accept""*/*");  
  50.         retrieveEntityReq.responseType = "arraybuffer";  
  51.   
  52.         retrieveEntityReq.onreadystatechange = function()  
  53.         {  
  54.             if (retrieveEntityReq.readyState == 4 && retrieveEntityReq.status == 200) {  
  55.                 var binary = "";  
  56.                 var bytes = new Uint8Array(this.response);  
  57.   
  58.                 for (var i = 0; i < bytes.byteLength; i++)  
  59.                 {  
  60.                     binary += String.fromCharCode(bytes[i]);  
  61.                 }  
  62.                 var bdy = btoa(binary);  
  63.   
  64.                 CreateEmailAttachment(bdy);  
  65.             }  
  66.         };  
  67.         retrieveEntityReq.send();  
  68.     },  
  69.     getReportingSession: function()  
  70. {  
  71.         var selectedIds = Xrm.Page.data.entity.getId();  
  72.         var reportName = "abc.rdl";  
  73.         var reportGuid = // Report GUID - Replace with your report GUID  
  74.   
  75.             var pth = Xrm.Page.context.getClientUrl() + "/CRMReports/rsviewer/QuirksReportViewer.aspx";  
  76.   
  77.         var retrieveEntityReq = new XMLHttpRequest();  
  78.   
  79.         retrieveEntityReq.open("POST", pth, false);  
  80.   
  81.         retrieveEntityReq.setRequestHeader("Accept""*/*");  
  82.   
  83.         retrieveEntityReq.setRequestHeader("Content-Type""application/x-www-form-urlencoded");  
  84.   
  85.         retrieveEntityReq.send("id=%7B" + reportGuid + "%7D&uniquename=" + Xrm.Page.context.getOrgUniqueName() + "&iscustomreport=true&reportnameonsrs=&reportName=" + reportName + "&isScheduledReport=false&p:<parameters Name In ssrs>=" + selectedIds.toLowerCase().replace(/[^a-z0-9-]/g, ''));  
  86.         // p:<parameters Name In ssrs> :Is optional when you want to have parameter.  
  87.         var x = retrieveEntityReq.responseText.lastIndexOf("ReportSession=");  
  88.         var y = retrieveEntityReq.responseText.lastIndexOf("ControlID=");  
  89.   
  90.         var ret = new Array();  
  91.   
  92.         ret[0] = retrieveEntityReq.responseText.substr(x + 14, 24);  
  93.         ret[1] = retrieveEntityReq.responseText.substr(x + 10, 32);  
  94.   
  95.         return ret;  
  96.     },  
Hope this will help in your custom development. Leave your comment if you have any query.