Friday 11 March 2016

Send a PDF File as an attachment in Mail using java script 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 for based on the newelly created activityId.

STEP 1
CreateEmail: function () {
var email = new Object();
email.Subject = "Testing the sending of mail through java script";
SDK.REST.createRecord(email, "Email", EmailCallBack, function (error) { alert(error.message); });
},
STEP 2
When the Email record is created with sucessfull, Then we have to create activity party for that email.
// Email Call Back function
EmailCallBack: function (result) {
email1 = result;
var activityParty = new Object();
// Set the "party" of the ActivityParty // EntityReference of an entity this activityparty relatated to.
activityParty.PartyId = {
Id: Xrm.Page.context.getUserId(), // id of the the current user which becomes the sender
LogicalName: "systemuser"
};
// Set the "activity" of the ActivityParty
// EntityReference.
activityParty.ActivityId = {
Id: result.ActivityId,
LogicalName: "email"
};
// Set the participation type (what role the party has on the activity).
activityParty.ParticipationTypeMask = { Value: 1 }; // 1 mean Sender

SDK.REST.createRecord(activityParty, "ActivityParty", ActivityPartyCallBack, function (error) { alert(error.message); });
},
STEP 3
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:-
Generate PDF File Using Java Script
ActivityPartyCallBack: function (result2) {
// Generate the pdf file to attached to the Email.
var responseSession = getReportingSession();
encodePdf(responseSession);
},
// create a Email record with the attachement and other parameters.
CreateEmailAttachment: function (bdy) {
//Email attachment parameters
var activitymimeattachment = Object();
activitymimeattachment.ObjectId = Object();
activitymimeattachment.ObjectId.LogicalName = "email";
activitymimeattachment.ObjectId.Id = email1.ActivityId;
activitymimeattachment.ObjectTypeCode = "email",
activitymimeattachment.Subject = "File Attachment";
activitymimeattachment.Body = bdy;
activitymimeattachment.FileName = "xyz.pdf";
//Attachment call
activitymimeattachment.MimeType = "application/pdf";

SDK.REST.createRecord(activitymimeattachment, "ActivityMimeAttachment",ActivityMimeAttachmentCallBack, function (error) { alert(error.message); });
},
STEP 4 ActivityMimeAttachmentCallBack: function (result) {
var options = {
openInNewWindow: true
};
Xrm.Utility.openEntityForm("email", email1.ActivityId, null, options);
},
//Encode the binary output pdf file to create an attachement
encodePdf: function (responseSession) {

var retrieveEntityReq = new XMLHttpRequest();

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";

retrieveEntityReq.open("GET", pth, true);
retrieveEntityReq.setRequestHeader("Accept", "*/*");
retrieveEntityReq.responseType = "arraybuffer";

retrieveEntityReq.onreadystatechange = function () {
if (retrieveEntityReq.readyState == 4 && retrieveEntityReq.status == 200) {
var binary = "";
var bytes = new Uint8Array(this.response);

for (var i = 0; i < bytes.byteLength; i++) {
binary += String.fromCharCode(bytes[i]);
}
var bdy = btoa(binary);

CreateEmailAttachment(bdy);
}
};
retrieveEntityReq.send();
},
 Method to get the session in the form of Array getReportingSession: function () {
var selectedIds = Xrm.Page.data.entity.getId();
var reportName = "abc.rdl";
var reportGuid = // Report GUID - Replace with your report GUID

var pth = Xrm.Page.context.getClientUrl() + "/CRMReports/rsviewer/QuirksReportViewer.aspx";

var retrieveEntityReq = new XMLHttpRequest();

retrieveEntityReq.open("POST", pth, false);

retrieveEntityReq.setRequestHeader("Accept", "*/*");

retrieveEntityReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

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, ''));
// p:<parameters Name In ssrs> :Is optional when you want to have parameter.
var x = retrieveEntityReq.responseText.lastIndexOf("ReportSession=");
var y = retrieveEntityReq.responseText.lastIndexOf("ControlID=");

var ret = new Array();

ret[0] = retrieveEntityReq.responseText.substr(x + 14, 24);
ret[1] = retrieveEntityReq.responseText.substr(x + 10, 32);

return ret;
},
 Hope this would help in your custom development.
Leave you comment if you have any query.....