Example scripting for email notifications

Examples of scripting for email notifications.

Scripting examples for email notifications

A simple text string is the most basic example of the way a mail script works. This script prints out "Incident number - INC00001".
   template.print("Incident number - "+ current.number);
More advanced scripts, like this one, can be found by browsing through the base system email templates.
template.print("Summary of Requested items:<br />");  
var gr = new GlideRecord("sc_req_item");
gr.addQuery("request", current.sysapproval);
gr.query();
while(gr.next()) {
  template.print(gr.number + ":  " + gr.quantity + " X " + gr.cat_item.getDisplayValue() 
                   + " at " + gr.cat_item.price.getDisplayValue() + " each <br />");
}
To dynamically change field values within an email, use the following functions within <mail_script> syntax:
...
email.setFrom(current.caller_id.email);
email.setReplyTo("joe.employee@yourcompany.com");
email.setSubject("This is the new subject line");
email.setBody("This is the new body");
...
Using the instance_name property ensures that the notification still works when migrated between instances.
dothis();
 
function dothis(){
    var gr =new GlideRecord('sys_attachment');
    gr.addQuery('table_sys_id',current.sys_id);
    gr.query();while(gr.next()){
        template.print('Attachment: <a href="https://'+ gs.getProperty('instance_name')+'
            .service-now.com/sys_attachment.do?sys_id='+ gr.sys_id+'">'+ gr.file_name+'</a>');}}
You can specify copied and blind copied recipients by using the email object within a mail script.
//email.addAddress(type, address, displayname);
    email.addAddress("cc","john.copy@example.com","John Roberts");
    email.addAddress("bcc","john.secret@example.com","John Roberts");
The following is an example script to add users from watch_list as copied recipients.
if(!current.watch_list.nil()){
   //get watch list addresses and add to cc
   var watcherIds = current.watch_list.split(",");
 
   //get user records
   var user =new GlideRecord("sys_user");
   user.addQuery("sys_id", watcherIds);
   user.addQuery("notification",2); 
   //email
   user.addQuery("email","!=","");
   user.query();
 
   while(user.next()){
      //add to cc list    
      email.addAddress("cc", user.email, user.getDisplayValue());}}