Scripting Email Notifications in ServiceNow

How to use mail scripts within email notifications to call dynamic data and modify email related fields.

Scripting Email Notifications in ServiceNow

When sending notifications in ServiceNow it's extremely common to want to use values from the records you are dealing with.

While generally this is as easy expanding the fields list and clicking the value you want included, some times you need things that aren't included or that are a little more complex to source.

Below you can see a few examples of different scripting techniques you can use to pull complex values into your notifications. Each of the below examples makes use of mail scripts, I will include a brief overview of how to use a mail script below also.


How to call a mail script from within an email notification:

${mail_script:NameOfMailScriptHere}

Simple hello world mail script that prints the words "Hello World" where the above mail script call has been used.

(function runMailScript(/* GlideRecord */ current, /* TemplatePrinter */ template,
          /* Optional EmailOutbound */ email, /* Optional GlideRecord */ email_action,
          /* Optional GlideRecord */ event) {

          template.print("Hello World");

})(current, template, email, email_action, event);

Mail Script commands for specific uses:

These are all commands that are entered in the mail script, the mail script is then called from within the notification as above. You cannot put a mail script in the subject field of a notification, you must call the mail script from the message HTML field, if it is a script to modify the subject line you can include it anywhere in the message HTML field.

Modify the subject line of an email

email.subject = "My Subject Line Here";

Get the current value of the subject line of an email

email.getSubject();

Appending a custom value to the end of an existing email subject line

email.subject = email.getSubject() + " - Some text I wish to add";

Add an email address to the CC field or BCC field of an email, the general format is "Field Type / Email / Display Name" and before you ask, no, you cannot add to the "TO" field using this method, it only works with CC and BCC, yes I know, sad panda.

email.addAddress("CC",user.email.toString(),"John Smith");
email.addAddress("BCC",user.email.toString(),"John Smith");

Insert some values from a table using Glide Records

(function runMailScript(/* GlideRecord */ current, /* TemplatePrinter */ template,
          /* Optional EmailOutbound */ email, /* Optional GlideRecord */ email_action,
          /* Optional GlideRecord */ event) {
    
    	var gr = new GlideRecord("sys_user");
    	gr.addQuery("active","true");
	gr.query();
    	while(gr.next()){
            template.print("Hello "+gr.name+", welcome to my blog!");
            template.print("<br/>");
        }

})(current, template, email, email_action, event);