SNOWYCODE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
How To Write A Mail Script In ServiceNow
How To's

How To Write A Mail Script In ServiceNow

How To Write A Mail Script In ServiceNow

Introduction

Mails scripts (also called Notification Email Scripts) in ServiceNow are used to customize outbound email notifications. This dynamic tool allows the system to adjust email content based on specific conditions or criteria. For example, mail scripts can display specific incident data or conduct complex database queries.

Real-world Use Cases of Mail Scripts

Here are a couple of examples:

  1. Enhanced Reporting: Mail scripts can be used to include content in the emails that aren't directly tied to the specific form that triggers the notification. For example, it can aggregate and provide a brief table of the number of open incidents related to a specific issue in an email notification.
  2. Personalized User Experience: Mail scripts enable the creation of more personalized, user-specific emails by pulling relevant data from the user's record or related tables. For instance, you can fetch and display user-specific data such as their past request history or upcoming deadlines.

How To Invoke Mail Scripts

Mail scripts in ServiceNow are invoked from within the email notification or template. This is achieved by including ${mail_script:script name} tag in the body of the email. The 'script name' is the name of the mail script you've written. This allows the system to execute the script and dynamically alter the email content based on the logic of the script.

Steps to Create A Mail Script

To create a Mail script, follow these steps:

  1. Navigate to "System Notification > Email > Notification Email Scripts" in ServiceNow
  2. Click "New"
  3. Provide a unique name in the "Name" field
  4. In the "Script" field, write your JavaScript code that defines the functionality of the mail script
  5. Click "Submit" to save the script

A picture containing text, screenshot, software, multimedia softwareDescription automatically generated
Mail Script Creation

Variables That Are Accessible from Mail Scripts

When working with mail scripts, you have access to the following variables:

  1. template: The template variable allows you to print content from the mail script to the email message. You can use the template.print("message") method to include a specific message in the email body. Additionally, the template.space("number of spaces") method lets you add spaces within the email body.

  2. email_action: The email_action variable represents a GlideRecord object for the email notification (sysevent_email_action). It provides access to various properties and fields of the email notification, allowing you to retrieve information or perform actions specific to the notification.

  3. event: The event variable represents a GlideRecord object for the event that triggered the notification (sysevent). It gives you access to information about the event, such as the event parameters, enabling you to incorporate event-related data into your mail script.

  4. email: The email variable represents the EmailOutbound object, which provides methods to manipulate the email properties.
You can use the following methods from the email object:
  • addAddress: This method allows you to add additional recipients to the email. The type of parameter can be "cc" or "bcc".
  • setFrom: Use this method to override the sender address of the email.
  • setReplyTo: This method allows you to override the reply-to address of the email.
  • setSubject: Use this method to override the subject of the email message.
  • setBody: This method allows you to override the body of the email message.

Note: When using the setFrom and setReplyTo methods, make sure that the email addresses are in a valid format, such as "helpdesk@sn.com" or "Display Name helpdesk@sn.com". If the email address includes a "Display Name," it will take precedence over the instance's display name.

Example: Sending An Email Notification with A List Of Requested Items

In this example, we will create a mail script to generate an email notification that contains a summary of requested items. Specifically, we will focus on the requested items that are "Standard Laptops".

Step-by-Step Instructions:

First, create the mail script:

  1. Access your ServiceNow instance and navigate to the appropriate section for creating a mail script (System Notifications > Email > Notification Email Scripts)
  2. Create a new mail script and provide it with a meaningful name such as "standard_laptops_summary" (each word should be lowercase and separated with an underscore, so that it can be invoked in the email notification)
  3. Inside the mail script, utilize the template.print method to define the email content in a table format (as shown in the code snippet below)
 (function runMailScript( /* GlideRecord */ current, /* TemplatePrinter */ template,
    /* Optional EmailOutbound */
    email, /* Optional GlideRecord */ email_action,
    /* Optional GlideRecord */
    event) {

    // Print the summary heading with table formatting
    template.print('<table style="border-collapse: collapse;">');
    template.print('<tr>');
    template.print('<th style="border: 1px black; padding: 8px;">Number</th>');
    template.print('<th style="border: 1px black; padding: 8px;">Quantity</th>');
    template.print('<th style="border: 1px black; padding: 8px;">Item</th>');
    template.print('<th style="border: 1px black; padding: 8px;">Price</th>');
    template.print('</tr>');

    // Query the sc_req_item table for requested items where item is "Standard Laptop"
    var now_GR = new GlideRecord("sc_req_item");
    var sysID_of_Standard_Laptop = "04b7e94b4f7b4200086eeed18110c7fd";
    now_GR.addQuery("cat_item", sysID_of_Standard_Laptop);
    now_GR.query();

    // Loop through the requested items and print the details in table rows
    while (now_GR.next()) {
        template.print('<tr>');
        template.print('<td style="border: 1px black; padding: 8px;">' + now_GR.number + '</td>');
        template.print('<td style="border: 1px black; padding: 8px;">' + now_GR.quantity + '</td>');
        template.print('<td style="border: 1px black; padding: 8px;">' + now_GR.cat_item.getDisplayValue() + '</td>');
        template.print('<td style="border: 1px black; padding: 8px;">' + now_GR.cat_item.price.getDisplayValue() + '</td>');
        template.print('</tr>');
    }

    // Close the table
    template.print('</table>');

})(current, template, email, email_action, event);
  1. Save the mail script

Now that the mail script is created, it's time to configure the email notification:

  1. Set the "Notification Name" as a descriptive name for the email notification
  2. Specify the "Recipient(s)" or "Group(s)" who should receive the email
  3. Set the "Subject" of the email notification to a meaningful value, such as "Standard Laptops Requested Items Summary"
  4. In the email body, add the ${mail_script:standard_laptops_summary} tag to include the mail script content
  5. Customize any additional email content or formatting as desired
  1. Save the email notification
  2. Test the email notification by triggering the corresponding event or action in your system that would trigger the notification. Verify that the email contains the requested items summary for "Standard Laptops" only
  3. The output will look something like this:

ServiceNow Mail Script Output In Email Notification

Advanced Topics Of Mail Scripts

Mail scripts in ServiceNow aren't just limited to simple tasks.

They can execute nested database queries and apply complex logical conditions to display specific information in the email. For example, you can write a mail script to check if a user has any unresolved incidents from the past month and, if so, include a list of those incidents in the email.

Conclusion

Mail scripts offer a dynamic and customizable way of handling outbound email notifications in ServiceNow. By mastering them, you can provide more personalized, data-driven notifications to users, improve user experience and efficiency of communication. With best practices in place and an understanding of how to tackle common challenges, the potential benefits of mail scripts are never ending!

Looking for something else? Check out our other posts below!

Snowycode team
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Read more