How do I add multiple users to a watch_list through an inbound email action script?

klazarenko
Kilo Contributor

Hi there,

I need to add users to a watchlist automatically through an inbound email action. These users are in ServiceNow already, so I am not adding anyone new to the system.

In my script, I think I use... current.watch_list.setDisplayValue('Doe, John');
To get the person added to the list.
That would only work if I had 1user to add, but I have 4.

I've tried imputing their email addresses separated by commas, concatenating a string of user names and commas, etc...
Nothing is working.

Has anyone had any success adding multiple users to a watch_list through an inbound email action script?

Thanks!
Karen

4 REPLIES 4

Chris_Hann
ServiceNow Employee
ServiceNow Employee

List fields are stored as a comma-separated list of sys_id's, so your Script will have to find the User records and add them to the list. Note that if you're adding the users to an existing record, you'll have to ensure you don't add them if they're already watching the record. You script will look something like:


var emailAddresses = 'adela.cervantsz@example.com, alissa.mountjoy@example.com'
addToWatchList(emailAddresses);

function addToWatchList(emailAddresses) {
var watcherIDs = current.watch_list.toString().split(',');

var newWatchers = new GlideRecord('sys_user');
newWatchers.addQuery('email', 'IN', emailAddresses);
newWatchers.query();

while (newWatchers.next()) {
var isAlreadyWatching = current.watch_list.toString().indexOf(newWatchers.getUniqueValue()) != -1;
if (!isAlreadyWatching)
watcherIDs.push(newWatchers.getUniqueValue());
}

current.watch_list = watcherIDs.join(',');
}


klazarenko
Kilo Contributor

Hi Chris, thank you so much for your help. I applied your code and received processing errors advising "addToWatchList" wasn't defined. So I moved the function before it was called in the script and it worked! This is what it looked like in the end:

var emailAddresses = 'xxx@example.com, xxx@example.com, xxx@example.com';
function addToWatchList(emailAddresses) {
var watcherIDs = current.watch_list.toString().split(',');
var newWatchers = new GlideRecord('sys_user');
newWatchers.addQuery('email', 'IN', emailAddresses);
newWatchers.query();

while (newWatchers.next()) {
var isAlreadyWatching = current.watch_list.toString().indexOf(newWatchers.getUniqueValue()) != -1;
if (!isAlreadyWatching) {
watcherIDs.push(newWatchers.getUniqueValue());
}
}

current.watch_list = watcherIDs.join(',');
}

addToWatchList(emailAddresses);


Thank you so very much for your help! Much appreciated!


klazarenko
Kilo Contributor

Can I ask you one last question? Do you have any suggestions for what to check for when attachments don't come across?


Andrii
Kilo Guru

I find this article very helpful and hope you'll find it helpful for your task too *)