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
When the Email record is created with sucessfull, Then we have to create activity party for that email.
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
Leave you comment if you have any query.....
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 2When 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 3When 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.....
The best services of crm software you can call us I have read this blog that are really nice please get a chance to :- dealer crm and online lead management
ReplyDeleteThanks Jones for appreciate...
DeleteI mean, I know it was my choice to read, but I really thought you'd have something useful to talk about. All I hear is a bunch of complaining about something that you can fix if you weren't too busy seeking attention.
ReplyDeletehttp://www.redsqware.com/
Thanks for reading the blog and yes I can.
DeleteHello Pankaj,
ReplyDeleteIs this solution feasible for Reports in MS CRM online?
I could not get report session parameters.
Please share your thoughts.
Thanks,
Aleem
Hi Aleem,
ReplyDeleteThis works perfect and tested with online crm 2016.
If you see their is No parameter for report session method.
For more info you can refer my blog on generating report to PDF.
Hi pankaj..me getting report session I'd n all properly but when calling encodepdf method m facing problm response body is undefined....could you plz help me ...is any browser problm..m running in IE11
ReplyDeleteHi pankaj..me getting report session I'd n all properly but when calling encodepdf method m facing problm response body is undefined....could you plz help me ...is any browser problm..m running in IE11
ReplyDeleteHi pankaj..me getting report session I'd n all properly but when calling encodepdf method m facing problm response body is undefined....could you plz help me ...is any browser problm..m running in IE11
ReplyDeleteHi venkatesh,
DeleteCan you specify the version of CRM .
Try to replace this code in encodepdf method when calling XMLHttpRequest() request
var bdy = new Array();
retrieveEntityReq.open("GET", pth, false);
retrieveEntityReq.setRequestHeader("Accept", "*/*");
retrieveEntityReq.send();
bdy =retrieveEntityReq.responseBody.toArray();
Then encode the bdy value to encode64 for using as an attachement.
This comment has been removed by the author.
ReplyDeleteThis comment has been removed by the author.
DeleteThis comment has been removed by the author.
DeleteThis comment has been removed by the author.
DeleteThis comment has been removed by the author.
ReplyDeleteHi,
ReplyDeleteI am trying same code in Dynamic 365 crm online and I get error while retrieving reportsessionid
"window.location.href = '/_common/error/errorhandler.aspx?BackUri=https%3a%2f%2fabc.crm4.dynamics.com%2f%2fWebResources%2fnew_test2.html%3fpreview%3d1&ErrorCode=0x8004832C&Parm0=%0d%0a%0d%0a&Parm1=&RequestUri=%2fCRMReports%2frsviewer%2fQuirksReportViewer.aspx&user_lcid=1033'
Hi Pankaj, I'm trying with this code in Dynamic 365 too. I can generated the pdf file, but I can't read it because It is wrong. the size of this pdf file always is 357 bytes. What do you think is happening? by the way, how I can sure it is takeing the correct rdl report? thanks
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteHello Pankaj Sir,
ReplyDeleteIf i only want to create a pdf file of my report, what can i do?
Hi Pankaj,
ReplyDeleteThanks for your blog, i uesd your code in my dynamics 365 online version , Email and pdf attachment creating successfully , when open attached pdf i got "Failed load Pdf Document" Error How to resolve this issue please help me to do this
Hi Pankaj,
ReplyDeleteGreat blog. I am trying to do something similar in c# inside a plugin or custom workflow activity (for Dynamics 365 online). Similar to your JS example, can this be done in C# i.e. rendering a report to pdf (for Dynamics 365 online)? Do you have any c# example? Thanks in advance.
Regards,
Joe
This comment has been removed by the author.
ReplyDeleteHi Pankaj,
ReplyDeleteStandard code:if (retrieveEntityReq.readyState == 4 && retrieveEntityReq.status == 200)
in this Line i am getting values like (retrieveEntityReq.readyState == 1 and retrieveEntityReq.status == null).Please let me know where am wrong
Thank
Hi,
ReplyDeleteWe have utilized the code successfully in CRM Online. We have upgrade to version 9.0 scheduled this month and wondered if anyone could validate that solution works in that version.
Thanks
Hi Pankaj, I am trying to use this code in CRM online, 9.2 version, but its not working t, can you please help me to write same code for Dynamics CRM 365, 9.2 version
ReplyDelete