What are ServiceNow Email Scripts?

ServiceNow email scripts are server-side scripts written in JavaScript that generate dynamic content for email notifications. They allow you to retrieve, format, and insert relevant data into email templates before sending them.

Email scripts are primarily used to customize email notifications by adding dynamic content like ticket details, user information, and system-generated values.

Where to Use Email Scripts?

Email scripts can be used in email notifications, inbound email actions, and email templates to dynamically populate values. The primary use cases include.

How do you create an email script in ServiceNow?

To create an email script in ServiceNow,

  1. Navigate to System Notification > Email > Email Scripts.
  2. Click New to create a new email script.
  3. Enter a name and select the application scope.
  4. Write the JavaScript code in the script field.
  5. Click Submit.

Example. Simple Email Script

This script fetches an incident's number and short description.

var incident = current;
var emailBody = "Incident Number: " + incident.number + "\n";
emailBody += "Short Description: " + incident.short_description;
emailBody;

How do you call an email script in an email notification?

To use this email script in a notification.

  1. Navigate to System Notification > Email > Notifications.
  2. Open or create a notification.
  3. In the Message field, use the following syntax to call the email script.
    ${email_script:your_script_name}
    
  4. Replace your_script_name with the actual name of your script.

Example. Email Script with Conditional Logic

The following script adds a message based on the incident priority.

var message = "";
if (current.priority == 1) {
    message = "This is a Critical Incident. Immediate attention required!";
} else {
    message = "This incident is under normal priority.";
}
message;

Call this script in the email notification using.

${email_script:priority_warning}

Example. Adding a Table of Related Tasks in Email

This script fetches all tasks related to an incident and formats them as a table.

var tasks = new GlideRecord('sc_task');
tasks.addQuery('parent', current.sys_id);
tasks.query();

var taskList = "<table border='1'><tr><th>Task Number</th><th>State</th></tr>";
while (tasks.next()) {
    taskList += "<tr><td>" + tasks.number + "</td><td>" + tasks.state.getDisplayValue() + "</td></tr>";
}
taskList += "</table>";
taskList;

This will display related tasks in an email notification in a structured format.

Best Practices for ServiceNow Email Scripts

Thoughts

ServiceNow email scripts are powerful tools for customizing email notifications dynamically. By leveraging JavaScript and Glide APIs, you can create flexible and data-rich emails that enhance communication within the platform.

Need help implementing email scripts? Feel free to reach out! bye until next time.