create Email and create attachement and send email on demand of workflow using js in smcrm

///creating the email
function emailSend() {
    debugger;
    var caseResult = caseRecordData();
    var activityPartyFrom = new Object();
    var userId = Xrm.Page.context.getUserId().replace("{", "").replace("}", "")
    var emailPartyEntities = [{
        PartyId: { LogicalName: CustomerId.LogicalName, Id: custId },
        ParticipationTypeMask: { Value: 2 }
    }, {
        PartyId: { LogicalName: "systemuser", Id: userId },// Xrm.Page.context.getUserName() { LogicalName: Xrm.Page.context.getUserName(), Id: userId },
        ParticipationTypeMask: { Value: 1 }
    }];
    var email = {
        Subject: Title,//"purushotham",//emailSubject, /* "MTC Microsoft CRM Proposal/Invoice - ApprovalRequested",*/
        MimeType: "text/html",
        Description: Description,
        email_activity_parties: emailPartyEntities
    };
    XrmSvcToolkit.createRecord({
        entityName: "Email",
        entity: email,
        async: false,
        successCallback: function (result1) {
            if (result1 != null) {
                CreateEmailAttachment(result1);
                sendEmailRequest(result1);
                window.close();
                window.open(Xrm.Page.context.getClientUrl() + "/main.aspx?etc=4202&extraqs=%3f_gridType%3d4202%26etc%3d4202%26id%3d%257b" + result1.ActivityId + "%257d%26preloadcache%3d1405921670796%26rskey%3d663904753&histKey=568832271&newWindow=true&pagetype=entityrecord&rskey=663904753#181750724");
            }
        },
        errorCallback: function (error) {
            alert("There was an error when creating the email record");
        }
    });
}
var url = window.location.href;
var entData = url.split("=")[1];
var entName = entData.split(".")[1];
var entId = entData.split(".")[0];
//var email = null;
//var title = null;
var CustomerId = null;
var Description = null;
var EmailAddress = null;
var IncidentId = null;
var OwnerId = null;
var Title = null;
var custname = null;
var custId = null;
////retrieve the cse entity information
function caseRecordData() {
    if (entName == "incident") {
        entName = "Incident";
    }
    XrmSvcToolkit.retrieve({
        entityName: "Incident",
        id: entId,
        select: ["CustomerId", "Description", "EmailAddress", "IncidentId", "OwnerId", "Title"],
        expand: ['TransactionCurrency_Incident'],
        async: false,
        successCallback: function (result) {
            CustomerId = result.CustomerId;
            // Description = result.Description;
            //EmailAddress = result.EmailAddress;
            IncidentId = result.IncidentId;
            OwnerId = result.OwnerId;
            Title = result.Title;
            if (CustomerId != null && CustomerId != undefined) {
                if (CustomerId.LogicalName == "account") {
                    custname = "Account";
                } else if (CustomerId.LogicalName == "contact") {
                    custname = "Contact";
                }
                custId = CustomerId.Id;
            }

            XrmSvcToolkit.retrieve({
                entityName: custname,
                id: custId,
                select: ["EMailAddress1", "Description"],
                async: false,
                successCallback: function (result) {
                    Description = result.Description;
                    EmailAddress = result.EMailAddress1;
                },
                errorCallback: function (error) {
                    alert(error.message);
                }
            });
        },
        errorCallback: function (error) {
            alert(error.message);
        }
    });
}

//creating the email attchements based on notes
function CreateEmailAttachment(result) {
    retrieveEmailNote();
    var enttname = "email";
    if (notesCol !== 0) {
        for (var i = 0; i < notesCol.length; i++) {
            var exten = null;
            var lookup = {};
            lookup.Id = result.ActivityId;//"13E90638-79E5-E711-A968-000D3AF05213";
            lookup.LogicalName = "email";//window.top.opener.Xrm.Page.data.entity.getEntityName();
            var obj = {};
            obj.Subject = notesCol[i].subject;//"File Upload -" + arrayStorage[i].name;
            obj.Body = notesCol[i].documentbody; //"purushotham body"; //Convert.ToBase64String(notesCol[i].documentbody);// "purushotham body";// notesCol[i].documentbody;//""//arrayStorage[i].body;
            obj.FileName = notesCol[i].filename;//arrayStorage[i].name;
            obj.FileSize = notesCol[i].filesize;
            exten = "application/" + notesCol[i].mimetype.split('/')[1];
            obj.MimeType = exten;//notesCol[i].mimeType;//exten;
            obj.ObjectTypeCode = "email";//notesCol[i].objecttypecode;//"5";//"4202"//notesCol[i].objecttypecode;//custname;//notesCol[i].objecttypecode;//custname;//"email";//selectedEntityName != "" && selectedEntityName != undefined ? selectedEntityName : window.top.opener.Xrm.Page.data.entity.getEntityName();
            obj.ObjectId = lookup; //result.ActivityId//lookup;//notesCol[i].objectid;//result.ActivityId//notesCol[i].objectid;//custId; //notesCol[i].objectid;//custId;//result.ActivityId; //Accountidref;
            XrmSvcToolkit.createRecord({
                entityName: "ActivityMimeAttachment",
                entity: obj,
                async: false,
                successCallback: function (result) {
                    if (i === notesCol.length - 1) {
                        if (notesCol.length > 1) {
                            Xrm.Utility.alertDialog("Files uploaded successfully");
                        } else {
                            Xrm.Utility.alertDialog("File uploaded successfully");
                        }
                        notesCol = [];
                    }
                },
                errorCallback: function (error) {
                    Xrm.Utility.alertDialog(error.message);
                    notesCol = [];
                }
            });
        }
    }
}
//retrieving the notes based on case entity
var notesCol = null;
function retrieveEmailNote() {
    notesCol = null;
    var notesFetch;
    var IsTrue = false;
    SDK.Metadata.RetrieveEntity(SDK.Metadata.EntityFilters.Attributes, EntityName, null, false,
     function (entitydata) {
         for (var i = 0; i < entitydata.Attributes.length; i++) {
             if (entitydata.Attributes[i].LogicalName === EntityName + "id") {
                 IsTrue = true;
                 break;
             }
         }
     },
     function (error) {
         Xrm.Utility.alertDialog(error.message);
     });

    notesFetch = '<fetch version="1.0" output-format="xml-platform" mapping="logical" no-lock="true" distinct="false">'
+ '<entity name="annotation">'
+ '<attribute name="subject" />'
+ '<attribute name="notetext" />'
+ '<attribute name="filename" />'
+ '<attribute name="mimetype" />'
+ '<attribute name="isdocument" />'
+ '<attribute name="documentbody" />'
+ '<attribute name="filesize" />'
+ '<attribute name="objectid" />'
+ '<attribute name="objecttypecode" />'
+ '<attribute name="annotationid" />'
+ '<attribute name="ownerid" />'
+ '<attribute name="createdon" />'
+ '<order attribute="createdon" descending="true" />'
+ '<link-entity name="' + EntityName + '" from="' + EntityName + 'id" to="objectid" alias="ab">'
+ '<filter type="and">'
+ '<condition attribute="' + EntityName + 'id" operator="eq" uitype="' + EntityName + '" value="' + Id + '" />'
+ '</filter>'
+ '</link-entity>'
+ '</entity>'
+ '</fetch>';

    XrmSvcToolkit.fetch({
        fetchXml: notesFetch,
        async: false,
        successCallback: function (result) {
            if (result !== null && result.entities.length > 0) {
                notesCol = result.entities;
                //retrieveTotalAttachments(notes);
            }
        },
        errorCallback: function (error) {
            Xrm.Utility.alertDialog(error.message);
        }
    });
}
//send in the email through workflow
function sendEmailRequest(result) {
    //current entity email guid
    var functionName = "executeWorkflow >>";
    var query = "";
    workflowId = "1f5bee55-222e-4741-9318-b3236c88ba02";
    try {
        //Define the query to execute the action
        query = "workflows(" + workflowId.replace("}", "").replace("{", "") + ")/Microsoft.Dynamics.CRM.ExecuteWorkflow";
        var data = {
            "EntityId": result.ActivityId.replace("}", "").replace("{", "")
        };
        //Create request
        // request url
        //https://org.crm.dynamics.com/api/data/v8.2/workflows(“f0ca33cc-23fd-496f-80e1-693873a951ca”)/Microsoft.Dynamics.CRM.ExecuteWorkflow
        var req = new XMLHttpRequest();
        req.open("POST", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/" + query, false);
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.setRequestHeader("OData-MaxVersion", "4.0");
        req.setRequestHeader("OData-Version", "4.0");
        req.onreadystatechange = function () {
            if (this.readyState == 4 /* complete */) {
                req.onreadystatechange = null;
                if (this.status == 200) {
                    //success callback this returns null since no return value available.
                    var result = JSON.parse(this.response);
                } else {
                    //error callback
                    var error = JSON.parse(this.response).error;
                }
            }
        };
        req.send(JSON.stringify(data));

    } catch (e) {
        throwError(functionName, e);
    }
}

Comments

Popular posts from this blog

Basic Plugin Code in D365 using C#

CURD (Create, Update, Retrieve and Delete) Operation in D365 using Power Shell Script

Meta Data Using WebApiRequest