email marketing

How to properly send an email notification when a record is deleted in ServiceNow

Imagine this requirement: You have to send an email notification to a manager if a record is created, updated, or deleted from a certain table. All emails have to contain information from the record.

The “create” and “update” cases are simple: Create a notification record associated with the necessary table, and use the Fields picker in the Select Variables section of the notification record to add the necessary information.

The Issue

For the “delete” case, suppose you create a business rule that fires on “delete” only, with the following code:

gs.eventQueue('incident.deleted', current, current.caller_id) 

To test it, you go to the incident table and delete a record. You check the sys_email table, and nothing is in the outbox. Although the above code is presumably correct, there is an issue: The current record may not exist by the time the event gets fired and when the email would be generated.

There is an easy two-step solution to get this scenario to work, using the same business rule/event set up.

The Solution

First, although the documentation for gs.eventQueue() calls for a second parameter of a GlideRecord object (in the above case the ‘current’ object), you can successfully pass a parameter of ‘null’ in its place. This is used in situations where the event doesn’t have to be tied to a specific record in the system.

The second issue you will need to address is that the information gathered by using the Fields tree picker in the notification record will not add the necessary record information to the notification as the record no longer exists. You can get around this by passing an object in the gs.eventQueue() call. You will then have to parse the object in a email script to generate the email body.

The Code

First, create the event in the Event Registry and create your Notification record. Then, in your Business Rule, which runs on Delete, you will want to create your object and then pass that into your event call while also using the ‘null’ parameter:

var obj = {
"caller" = current.caller_id.getDisplayValue(),
"shortDesc" = current.short_description,
"category" = current.category.getDisplayValue(),

var json = JSON.stringify(obj)

gs.eventQueue('incident.deleted', null, json);

The final step is to parse the above code in a mail script that is referenced in your notification record. This will allow you to print out the information from the deleted record in the body of the email. Of course, you can pass as much information as needed to fulfill your requirement.

var obj = JSON.parse(event.parm1);

template.print('Caller: ' + obj.caller + '<br>');
template.print('Category: ' + obj.category + '<br>');
template.print('Short Description: ' + obj.shortDesc + '<br>');

More information

For more information on passing events in ServiceNow, see the documentation here.