Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Script help with Notification email script

dvelloriy
Kilo Sage

Hi Team, I have created a notification email script however its not working as expected and not showing an variables data on the notification.

 

Notification: Health status update

Message html: ${mail_script:health_status_variables}

 

Email Script: health_status_variables

 

Script:

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

var util = new global.GlobalServiceCatalogUtil();
var obj = util.getVariablesForTask(current);
for (var i = 1; i < obj.length; i++) {
if (obj[i].label != 'Form State')
template.print(obj[i].label + ' : ' + obj[i].display_value + '<br>');
}

})(current, template, email, email_action, event);
 
Can someone please advise?
 
 
2 REPLIES 2

Gangadhar Ravi
Giga Sage

Hi @dvelloriy  if you are trying to add variable to email please try below 

 

(function runMailScript(current, template, email, email_action, event) {

	// Add your code here

	template.print('Variables: <br/>');
	
	var variables = current.variables.getElements(); 
	for (var i=0;i<variables.length;i++) { 
		var question = variables[i].getQuestion();
		var label = question.getLabel();
		var value = question.getDisplayValue();
		if(label != ''){
			template.space(4);
			template.print('  ' + label + " = " + value + "<br/>");
		}
	} 

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

 

Please mark my answer correct and helpful if this works for you.

PARASHURAM R
Tera Contributor

 

  • The loop should start at 0, not 1, as arrays in JavaScript are zero-indexed.
  • It's good practice to ensure that the object exists before processing it in a loop.

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

    var util = new global.GlobalServiceCatalogUtil();
    var obj = util.getVariablesForTask(current);

    // Ensure the object exists and has variables before looping
    if (obj && obj.length) {
    for (var i = 0; i < obj.length; i++) { // Starting the loop from 0, as arrays are zero-indexed
    if (obj[i].label !== 'Form State') { // Avoid printing the 'Form State'
    template.print(obj[i].label + ' : ' + obj[i].display_value + '<br>');
    }
    }
    }

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

    mark my answer correct and helpful if this works for you.