Dynamically Display Recipient Email Addresses in Dynamics 365 Emails

Step-by-Step Guide: Dynamically Display Recipient Email Addresses in Dynamics 365 Emails

Introduction

Want to display recipient email addresses directly in the “To” field when sending emails in Dynamics 365? You can easily achieve this using JavaScript! This guide explains how to use JavaScript to dynamically display the recipient’s name and email address in the “To” field of an email in Dynamics 365.

To see the complete script, scroll straight to the bottom or click here 👈

Prerequisites

  • A basic understanding of Dynamics 365 and form customizations.
  • Familiarity with JavaScript development.

Step 1: Understand the Use Case

By default, Dynamics 365 email functionality doesn’t show detailed recipient information (e.g., name and email) in the “To” field. This script dynamically fetches and displays recipient details (name and email) for better clarity.

How it looks by default:

Image showing how it looks by default in the "to" field in the email entity.
Image showing how it looks by default in the “to” field in the email entity.

How it looks after a little customizations with JavaScript:

Image showing how it looks in the email form after applying the script for showing name and email in the "to" field.
Image showing how it looks in the email form after applying the script for showing name and email in the “to” field.

Step 2: Script Overview

The script is designed to:

  1. Retrieve recipient details based on their entity type (e.g., Contact, Account, Queue, System User).
  2. Format the recipient’s name and email into a human-readable string.
  3. Update the “To” field with these formatted details.

Step 3: Code Breakdown

a) Initialize the Script

The script uses an sdk object as a namespace to define the setEmailAddressInToField function:

var sdk = window.sdk || {};
(function () {
  "use strict";
  this.setEmailAddressInToField = async function (executionContext) {
    const formContext = executionContext.getFormContext();

Here, executionContext provides access to the form context in Dynamics 365.

b) Get the Current “To” Field Value

Retrieve the “To” field data:

let emailReceivers = formContext.getAttribute("to");
if (emailReceivers.getValue() !== null && emailReceivers.getValue().length > 0) {

This checks if the “To” field contains recipients.

c) Iterate Through Recipients

Iterate over each recipient and retrieve their details:

for (let emailReceiver of emailReceivers.getValue()) {
    const emailReceiverId = emailReceiver.id.replace(/{|}/g, "");
    const emailReceiverEntity = emailReceiver.entityType;
      
    const result = await Xrm.WebApi.retrieveRecord(
    emailReceiverEntity,
    emailReceiverId
    );

Here, the retrieveRecord function fetches the recipient’s record using their entity type and ID.

d) Map Recipient Data

Format the recipient’s name and email based on the entity type:

Contact mapping:

if (emailReceiverEntity === "contact") {
    const firstName = result["firstname"];
    const lastName = result["lastname"];
    const email = result["emailaddress1"] || "Missing email address";
    mappedName = `${firstName} ${lastName} (${email})`;
}

Accounts mapping:

if (emailReceiverEntity === "account") {
    let name = result["name"]
    let email = result["emailaddress1"] || "Missing email address"
    mappedName = `${name} (${email})`
}

System Users mapping:

if (emailReceiverEntity === "systemuser") {
    const firstName = result["firstname"];
    const lastName = result["lastname"];
    const email = result["internalemailaddress"] || "Missing email address";
    mappedName = `${firstName} ${lastName} (${email})`;
}

Queues mapping:

if (emailReceiverEntity === "queue") {
    let name = result["name"]
    let email = result["emailaddress"] || "Missing email address"
    mappedName = `${name} (${email})`
}

e) Update the “To” Field

The script pushes the formatted data into an array and sets it back to the ‘To’ field.

let toValues = [] // Initialize the array to collect values

toValues.push({
    name: mappedName,
    id: emailReceiver.id,
    entityType: emailReceiverEntity,
});
emailReceivers.setValue(toValues);

f) Error Handling

You can improve this error message based on your needs.

catch (error) {
    console.log("Error in setEmailAddressInToField:", error.message);
}

Step 4: Register the Script

  1. Save the script as a JavaScript web resource in Dynamics 365.
  2. Add the script to the email form and bind the setEmailAddressInToField function to the appropriate event (e.g., OnChange for the “To” field).

Step 5: Test the Functionality

  1. Open the email form in Dynamics 365.
  2. Add recipients to the “To” field.
  3. Verify that the script dynamically displays their names and email addresses.

It should look similar as in the gif below.

Gif showing how it looks after applying the script to the email form.
Gif showing how it looks after applying the script to the email form.

The Complete Script

Use the complete script below as is or customize to meet your needs.

var sdk = window.sdk || {}
;(function () {
  "use strict"
  this.setEmailAddressInToField = async function (executionContext) {
    const formContext = executionContext.getFormContext()
    let emailReceivers = formContext.getAttribute("to")
    try {
      if (
        emailReceivers.getValue() !== null &&
        emailReceivers.getValue().length > 0
      ) {
        let toValues = [] // Initialize the array to collect values

        for (let emailReceiver of emailReceivers.getValue()) {
          const emailReceiverId = emailReceiver.id.replace(/{|}/g, "")
          const emailReceiverEntity = emailReceiver.entityType

          const result = await Xrm.WebApi.retrieveRecord(
            emailReceiverEntity,
            emailReceiverId
          )

          let mappedName = ""

          if (emailReceiverEntity === "contact") {
            const firstName = result["firstname"]
            const lastName = result["lastname"]
            const email = result["emailaddress1"] || "Missing email address"
            mappedName = `${firstName} ${lastName} (${email})`
          }

          if (emailReceiverEntity === "systemuser") {
            let firstName = result["firstname"]
            let lastName = result["lastname"]
            let email =
              result["internalemailaddress"] || "Missing email address"
            mappedName = `${firstName} ${lastName} (${email})`
          }

          if (emailReceiverEntity === "queue") {
            let name = result["name"]
            let email = result["emailaddress"] || "Missing email address"
            mappedName = `${name} (${email})`
          }

          if (emailReceiverEntity === "account") {
            let name = result["name"]
            let email = result["emailaddress1"] || "Missing email address"
            mappedName = `${name} (${email})`
          }

          // Add each mapped name to the array
          toValues.push({
            name: mappedName,
            id: emailReceiver.id,
            entityType: emailReceiverEntity,
          })
        }
        emailReceivers.setValue(toValues)
      }
    } catch (error) {
      console.log("Error in setEmailAddressInToField:", error.message)
    }
  }
}).call(sdk)

Conclusion

This solution aims to simplify verifying recipient details in Dynamics 365 emails, making communication clearer and more efficient. Hope it helps you and your customers with email workflows!

Resources

Walkthrough: Write your first client script in model-driven apps – Power Apps | Microsoft Learn

attribute.getValue (Client API reference) – Power Apps | Microsoft Learn

setValue (Client API reference) – Power Apps | Microsoft Learn


For More Content See the Latest Posts