Gif showing how to set the queue as the email sender based the queue that an incoming email was sent to.

How to Setting the Queue as Email Responder on Emails in Dynamics 365

Email management is a critical aspect of business communication, and automating email responses can significantly improve productivity. In Dynamics 365, you have the flexibility to customize and set the queue as the email responder, ensuring that emails are sent from the appropriate queue. This blog post explores two different scenarios for achieving this functionality using JavaScript and the Dynamics 365 Web API.

Setting the Stage

Before diving into the code, let’s provide a brief overview of the scenarios we’ll be addressing. In Dynamics 365, when dealing with email entities, there are two important concepts: the regarding record and the email sender. The regarding record represents the object (e.g., contact, account, case) with which the email is associated, while the email sender denotes the entity (e.g., user, queue) responsible for sending the email. Our goal is to automatically set the queue as the email sender based on either the queue that a case was added to or the queue that an incoming email was sent to.

Prerequisites

Before we proceed with the implementation, make sure you have the following:

  • Access to a Dynamics 365 environment
  • Administrator or customizer privileges to modify entity forms and add JavaScript code

Scenario 1: Setting the Queue as Email Sender for Cases

In this scenario, we’ll focus on automatically setting the queue that a case was added to as the email sender. This ensures that any outgoing emails related to the case will be sent from the appropriate queue. Here’s how you can achieve this:

Step 1: Create a Namespace

To avoid conflicts with existing JavaScript code, it’s recommended to create a namespace for your code. This namespace will encapsulate the functions we’ll define. Place the following code at the beginning of your JavaScript file:

// Create a namespace for the code
var sdk = window.sdk|| {};

In this case, all the functions defined in this library can be used as sdk.[functionName]. You should choose a namespace that matches your solution publisher name according to the best practice from Microsoft the can be found here: Walkthrough: Write your first client script in model-driven apps – Power Apps | Microsoft Learn.

Step 2: Define the Email Responder Function

Next, we’ll define the function setQueueAsEmailSender, which will be triggered when the email form is loaded. This function retrieves the form context, determines the form type, and sets the selected queue as the email sender. Add the following code:

(function () {
    "use strict";

    this.setQueueAsEmailSender = async function (executionContext) {
        // Get the form context
        const formContext = executionContext.getFormContext();

        // Get the form type of the loading record
        const formType = formContext.ui.getFormType();

        // Check if the form is of type Create or Update
        if (formType === 1 || formType === 2) {
            // Get the Queue from the regarding record by using the helper function
            const queue = await this._getRegardingQueue(formContext);

            // Check if Email has a regarding value
            if (queue !== null) {
                // Set the Queue as Sender in the email message
                formContext.getAttribute("from").setValue(queue);
            }
        }
    };

    // In step 3 the function for retrieving the regarding queue goes here
}).call(sdk);

Step 3: Retrieve the Regarding Queue

We need to retrieve the regarding queue of the current email record. Add the following code within the self-invoking function, see the comment in the previous code example and place it below the comment. Or wait until the end where the complete script is😉

this._getRegardingQueue = async function (formContext) {
    // Get regarding of the current email record
    const regardingObject = formContext.getAttribute("regardingobjectid").getValue();
    // Check if Email has a regarding value
    if (regardingObject !== null) {
        // Get regarding record id
        const regardingObjectId = regardingObject[0].id.replace(/{|}/g, "");
        // Retrieves the regarding record of the email
        const queueItemResult = await Xrm.WebApi.retrieveMultipleRecords("queueitem", `?$filter=_objectid_value eq ${regardingObjectId}`);
        // Check if the the result from WebApi query contains value by checking the length of the result
        if (queueItemResult.entities.length !== 0) {
            // Get values from Queue Item to find the Queue to set as sender
            const queueId = queueItemResult.entities[0]["_queueid_value"];
            const queueEntityType = queueItemResult.entities[0]["_queueid_value@Microsoft.Dynamics.CRM.lookuplogicalname"];
            const queueName = queueItemResult.entities[0]["_queueid_value@OData.Community.Display.V1.FormattedValue"];

            // Create a Queue Object to set as Sender in Email
            let queue = new Array();
            queue[0] = new Object();
            queue[0].id = queueId;
            queue[0].entityType = queueEntityType;
            queue[0].name = queueName;

            // Return queue object to main function
            return queue;
        }
    }
    // Return empty queue object to main function
    return null;
}

Step 4: Completing the script

When adding it all together it looks like the code below.

var sdk = window.sdk || {};
(function () {
    "use strict"
    this.setQueueAsEmailSender = async function (executionContext) {
        // Get the form context
        const formContext = executionContext.getFormContext();
        // Get the form type of loading record
        const formType = formContext.ui.getFormType();
        // Check if the form is of type Create or Update
        if (formType === 1 || formType === 2) { 
            // Get the Queue from the regarding record by using helper function
            const queue = await this._getRegardingQueue(formContext);
            // Check if Email has a regarding value
            if (queue !== null) {
                // Set the Queue as Sender in the email message
                formContext.getAttribute("from").setValue(queue);
            }
        }
    }
    this._getRegardingQueue = async function (formContext) {
        // Get regarding of the current email record
        const regardingObject = formContext.getAttribute("regardingobjectid").getValue();
        // Check if Email has a regarding value
        if (regardingObject !== null) {
            // Get regarding record id
            const regardingObjectId = regardingObject[0].id.replace(/{|}/g, "");
            // Retrieves the regarding record of the email
            const queueItemResult = await Xrm.WebApi.retrieveMultipleRecords("queueitem", `?$filter=_objectid_value eq ${regardingObjectId}`);
            // Check if the the result from WebApi query contains value by checking the length of the result
            if (queueItemResult.entities.length !== 0) {
                // Get values from Queue Item to find the Queue to set as sender
                const queueId = queueItemResult.entities[0]["_queueid_value"];
                const queueEntityType = queueItemResult.entities[0]["_queueid_value@Microsoft.Dynamics.CRM.lookuplogicalname"];
                const queueName = queueItemResult.entities[0]["_queueid_value@OData.Community.Display.V1.FormattedValue"];

                // Create a Queue Object to set as Sender in Email
                let queue = new Array();
                queue[0] = new Object();
                queue[0].id = queueId;
                queue[0].entityType = queueEntityType;
                queue[0].name = queueName;

                // Return queue object to main function
                return queue;
            }
        }
        // Return empty queue object to main function
        return null;
    }
}).call(sdk);

Step 5: Upload your code as a web resource

Now that the code is ready, we need to upload it into our solution and add it to the email form. To do this you can check out the post below or the documentation site in step 1 or from another where we go more in detail on how to do it here: How to add JavaScript to form on load in Dynamics 365.

Step 6: The final result

See the animated gif below to see the result.

Gif showing how to automatically set the queue as the email sender based on either the queue that a case was added to.

Elevate your programming career with “The Clean Coder: A Code of Conduct for Professional Programmers” by Robert C. Martin. Gain integrity, deliver high-quality code, and meet deadlines like a pro. This book provides practical advice, real-world examples, and valuable insights for developers at all levels. Enhance your skills and work ethic to become a respected and reliable programmer.

Please note that some of the links in this post are affiliate links. This means that we may earn a small commission when you make a purchase through those links. However, rest assured that it won’t cost you any extra. Your support fuels our late-night coding sessions and debugging snacks, allowing us to continue our tech adventures. Join the coding party and shop with confidence.

Scenario 2: How to Set the Receiving Queue that the email was sent to as Email Responder in Dynamics 365

Next up, automatically set the queue as the email sender based on the queue that an incoming email was sent to.

Step 1: Creating a Namespace

We begin by creating a namespace to encapsulate our code and avoid conflicts with existing JavaScript code.

// Create a namespace for the code
var sdk = window.sdk || {};

Step 2: Defining the Email Responder Function

Next, we define the function setQueueAsEmailSender that will be triggered when the email form is loaded. This function retrieves the form context, determines the form type, and retrieves the queue from the regarding record using a helper function.

(function () {
    "use strict";

    // Set the selected queue as the email sender
    this.setQueueAsEmailSender = async function (executionContext) {
        // Get the form context
        const formContext = executionContext.getFormContext();

        // Get the form type of the loading record
        const formType = formContext.ui.getFormType();

        // Check if the form is of type Create or Update
        if (formType === 1 || formType === 2) {
            // Get the Queue from the regarding record by using the helper function
            const emailSender = await this._getRegardingQueue(formContext);

            // Check if the email has a regarding value
            if (emailSender !== null) {
                // Set the Queue as Sender in the email message
                formContext.getAttribute("from").setValue(emailSender);
            }
        }
    };

Step 3: Retrieving the Regarding Queue and Email Sender

Within the _getRegardingQueue function, we retrieve the details of the email sender from the parent email record. This includes the ID, entity type, and name of the email sender. If the email sender is a queue, we create a queue object with the corresponding details and return it to the main function. Otherwise, we return null to indicate that there is no queue as an email sender and instead sets the user’s record.

this._getRegardingQueue = async function (formContext) {
        // Get the ID of the current email entity
        let emailId = formContext.data.entity.getId().replace(/{|}/g, '');

        // Retrieve the parent email of the current email
        let currentEmail = await Xrm.WebApi.retrieveRecord("email", emailId, "?$select=_parentactivityid_value");

        // Get the ID of the parent email
        let parentEmailId = currentEmail["_parentactivityid_value"];

        const queueItemResult = await Xrm.WebApi.retrieveMultipleRecords("queueitem", `?$filter=_objectid_value eq ${parentEmailId}`);

        // Check if the result from WebApi query contains value by checking the length of the result
        if (queueItemResult.entities.length !== 0) {
            // Get values from Queue Item to find the Queue to set as sender
            const queueId = queueItemResult.entities[0]["_queueid_value"];
            const queueEntityType = queueItemResult.entities[0]["_queueid_value@Microsoft.Dynamics.CRM.lookuplogicalname"];
            const queueName = queueItemResult.entities[0]["_queueid_value@OData.Community.Display.V1.FormattedValue"];

            // Create a Queue Object to set as Sender in Email
            let queue = [{
                id: queueId,
                entityType: queueEntityType,
                name: queueName
            }];

            // Return queue object to the main function
            return queue;
        } else {
            // Return null to the main function if there's no email sender
            return null;
        }
    };

Step 5: Putting It All Together

To summarize, the code snippet integrates the above functions into a cohesive structure. By executing the setQueueAsEmailSender function when the email form is loaded, it retrieves the queue associated with the parent email record and sets it as the email sender if it exists.

// Create a namespace for the code
var sdk = window.sdk || {};

// Use a self-invoking function to create a private scope
(function () {
    "use strict";

    // Set the selected queue as the email sender
    this.setQueueAsEmailSender = async function (executionContext) {
        // Get the form context
        const formContext = executionContext.getFormContext();

        // Get the form type of the loading record
        const formType = formContext.ui.getFormType();

        // Check if the form is of type Create or Update
        if (formType === 1 || formType === 2) {
            // Get the Queue from the regarding record by using the helper function
            const emailSender = await this._getRegardingQueue(formContext);

            // Check if the email has a regarding value
            if (emailSender !== null) {
                // Set the Queue as Sender in the email message
                formContext.getAttribute("from").setValue(emailSender);
            }
        }
    };

    // Get the queue from the regarding record of the current email
    this._getRegardingQueue = async function (formContext) {
        // Get the ID of the current email entity
        let emailId = formContext.data.entity.getId().replace(/{|}/g, '');

        // Retrieve the parent email of the current email
        let currentEmail = await Xrm.WebApi.retrieveRecord("email", emailId, "?$select=_parentactivityid_value");

        // Get the ID of the parent email
        let parentEmailId = currentEmail["_parentactivityid_value"];

        const queueItemResult = await Xrm.WebApi.retrieveMultipleRecords("queueitem", `?$filter=_objectid_value eq ${parentEmailId}`);

        // Check if the result from WebApi query contains value by checking the length of the result
        if (queueItemResult.entities.length !== 0) {
            // Get values from Queue Item to find the Queue to set as sender
            const queueId = queueItemResult.entities[0]["_queueid_value"];
            const queueEntityType = queueItemResult.entities[0]["_queueid_value@Microsoft.Dynamics.CRM.lookuplogicalname"];
            const queueName = queueItemResult.entities[0]["_queueid_value@OData.Community.Display.V1.FormattedValue"];

            // Create a Queue Object to set as Sender in Email
            let queue = [{
                id: queueId,
                entityType: queueEntityType,
                name: queueName
            }];

            // Return queue object to the main function
            return queue;
        } else {
            // Return null to the main function if there's no email sender
            return null;
        }
    };
}).call(sdk);

Step 5: Upload your code as a web resource

Now that the code is ready, upload you code as a web resource and add it on the on load event as described in scenario 1.

Step 6: The final result

See the animated gif below to see the result.

Gif showing how to set the queue as the email sender based the queue that an incoming email was sent to.

Conclusion

Automating email responses is a valuable feature in Dynamics 365, and setting the receiving queue as the email responder enhances efficiency in email management. By following the step-by-step guide provided in this blog post, you can implement this functionality using JavaScript code. Feel free to adapt and customize the code to suit your specific requirements.

Remember to test the code thoroughly in a development or sandbox environment before deploying it to production. This ensures that it functions as intended and does not adversely impact your Dynamics 365 instance.

Hope this blog post has been informative and helpful. If you have any questions or need further assistance, please don’t hesitate to reach out. Happy coding!


For More Content See the Latest Posts