Email Notifications Archives - ServiceNow Guru https://servicenowguru.com/category/email-notifications-system-definition/ ServiceNow Consulting Scripting Administration Development Tue, 28 May 2024 21:49:32 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.2 https://servicenowguru.com/wp-content/uploads/2024/05/cropped-SNGuru-Icon-32x32.png Email Notifications Archives - ServiceNow Guru https://servicenowguru.com/category/email-notifications-system-definition/ 32 32 HTML-formatted Email Client Message Text https://servicenowguru.com/email-notifications-system-definition/htmlformatted-email-client-message-text/ https://servicenowguru.com/email-notifications-system-definition/htmlformatted-email-client-message-text/#comments Wed, 12 Dec 2012 13:42:27 +0000 https://servicenowguru.wpengine.com/?p=4712 The ServiceNow email client is a great way to allow technicians to send ad-hoc email notifications from within ticket and other forms. One common request I’ve seen for the email client is to allow the creation of html-formatted messages. Of course, it’s possible to manually code the HTML, but it’s much easier with a WYSIWYG

The post HTML-formatted Email Client Message Text appeared first on ServiceNow Guru.

]]>
The ServiceNow email client is a great way to allow technicians to send ad-hoc email notifications from within ticket and other forms. One common request I’ve seen for the email client is to allow the creation of html-formatted messages. Of course, it’s possible to manually code the HTML, but it’s much easier with a WYSIWYG editor to help with code generation and formatting.

In this post, I’ll show you a technique that Valor Poland shared with me a year or so ago that changes the email client ‘Message Text’ field to an HTML-based field for this purpose.

HTML Email Client

The solution here is actually very simple…if you know where to look. As an ‘admin’ user, simply navigate to ‘System Logs – Emails’ and open an email log form. Once there, right-click the ‘Body’ field and select ‘Personalize – Dictionary’. Finally, change the field ‘Type’ value to ‘html’ and update the dictionary record.

Email Log HTML Type

The ‘Body’ field on the email log table is actually shared between the email log and email client forms. Now that you’ve updated the field type to html, you should see this change reflected in your email client form as well!

The post HTML-formatted Email Client Message Text appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/email-notifications-system-definition/htmlformatted-email-client-message-text/feed/ 14
Approval Email Mailto Image Links https://servicenowguru.com/email-notifications-system-definition/approval-email-mailto-image-links/ https://servicenowguru.com/email-notifications-system-definition/approval-email-mailto-image-links/#comments Thu, 19 May 2011 13:15:13 +0000 https://servicenowguru.wpengine.com/?p=3678 Last day at Knowledge11! What a great conference! I’ve had a great time meeting with so many awesome people this week. Yesterday Ian Broz and I were helping Karen Lazarenko during a 1-on-1 (maybe 2-on-1 in this case) session. She had a cool idea to make approval request emails coming from her system a little

The post Approval Email Mailto Image Links appeared first on ServiceNow Guru.

]]>
Last day at Knowledge11! What a great conference! I’ve had a great time meeting with so many awesome people this week. Yesterday Ian Broz and I were helping Karen Lazarenko during a 1-on-1 (maybe 2-on-1 in this case) session. She had a cool idea to make approval request emails coming from her system a little bit more intuitive by replacing or modifying the ‘mailto’ reply text links for approval and rejection with images that more clearly distinguished the links and the purpose of the email.

The challenge that we faced was how to easily add those images while maintaining the mailto functionality and populating the correct information (including the watermark ID) on the reply email. Here’s a screenshot of the solution we came up with. Read on to see how we did it!

Approval Email Images

This post is not intended to be a full explanation of the approval email notification process but I think a short explanation is helpful in understanding the problem we faced. When an approval record is put into a requested state, it triggers an event that sends out an approval email corresponding with the task the approval is associated with. The approval email (and corresponding email template) are chosen based on the task type and event triggered. For request tickets the email template is called ‘request.itil.approve.role’ and everything else uses the ‘change.itil.approve.role’ email template.

Approval templates actually go one step further by including special mailto links within the email that allow you to show ‘Approve’ and ‘Reject’ reply links directly in the email. This makes it a little bit easier for your users to process these approvals directly from their email client. The template code that does this looks like this…

${mailto:mailto.approval}

What this says is that the system will construct a mailto reply link in the email based on the ‘mailto.approval’ email template. The ‘mailto.rejection’ template serves the same purpose. Each of these two templates contains the actual text for the mailto link that pulls in the number of the task to be approved as part of the link.

Click here to approve ${sysapproval}

The end result of this setup is an email notification with a couple of links for users to approve or reject directly from their email client.

Approval Email

So…now to add images. One idea would be to modify the template code to accomplish this. The challenge is that the ‘${mailto:mailto.approval}’ command in our first template automatically adds some important information (our reply watermark ID) to the reply email for us and there’s not another simple way to replace that functionality. The simplest solution in this case was to intercept the email on its way out of the system (after the original mailto link had been formatted) and modify that piece of HTML to include our image tags. This technique is something I’ve described before on this blog if you want to read more.

All of this can be done in a simple business rule on the ‘sys_email’ table. The business rule runs when the email record is being sent and corresponds with the approval table. Then it looks for some specific text that is included only in the approval templates…’Click here to approve’ and ‘Click here to reject’, and replaces it with an image tag. The only thing you’ll need to modify in the script below are the URLs for the images themselves to point to your own instance or other publicly-available images of your choosing.

‘Add approval images’ Business Rule
Name: Add approval images
Table: Email (sys_email)
When: Before
Insert: True
Condition: current.target_table == ‘sysapproval_approver’ && current.type == ‘send-ready’
Script:

current.body = current.body.replace('Click here to approve', '<img src="https://demo.service-now.com/images/workflow_approved.gif" />');
current.body = current.body.replace('Click here to reject', '<img src="https://demo.service-now.com/images/workflow_approval_rejected.gif" />');

Here is the end result…

Approval Email Images

The post Approval Email Mailto Image Links appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/email-notifications-system-definition/approval-email-mailto-image-links/feed/ 17
Sending iCalendar Invites from any Task table https://servicenowguru.com/email-notifications-system-definition/sending-calendar-invites-task-table/ https://servicenowguru.com/email-notifications-system-definition/sending-calendar-invites-task-table/#comments Thu, 09 Dec 2010 13:08:36 +0000 https://servicenowguru.wpengine.com/?p=1707 ServiceNow has a pretty simple one-way Outlook calendar integration that you can use to send out iCal meeting requests and updates to assignees involved with a Change request. I’m often asked if this functionality can be used for meeting invites in other tables as well. The answer is Yes! This hasn’t really been documented because

The post Sending iCalendar Invites from any Task table appeared first on ServiceNow Guru.

]]>
ServiceNow has a pretty simple one-way Outlook calendar integration that you can use to send out iCal meeting requests and updates to assignees involved with a Change request. I’m often asked if this functionality can be used for meeting invites in other tables as well. The answer is Yes! This hasn’t really been documented because it relies on some legacy technology that really isn’t that prominent in the system anymore. In this article, I’ll show you the pieces that make this calendar integration work by showing you how to set the integration up for the change task table.

Please make sure you can send invites from change requests in your system before attempting this custom setup. If you can’t get change requests to work you’ll need to contact ServiceNow support.

The out-of-box iCalendar integration for Change requests relies on a few different pieces. Most of the pieces are actually standard email notification business rules, events, and templates. The real mystery to this integration lies in the start/end date mappings for the meeting request. These are important because they define the fields on the task that the email template pulls its dates from. Once you get this set up correctly all you’ve really got to do is set up some standard email notifications with a template that I’ll show you below.

Setting up the start/end date field mappings

Note: Since we’re basing our setup off of the out-of-box Change request setup you can use the ‘icalendar.change_request’ map as a reference while setting this up for another table.

–Navigate to the legacy ‘Import Export Map’ table by typing ‘sys_impex_map.list’ in your left navigation filter.
–We’ll create a new entry that ends up looking like this…

–Create the map entry as shown in the image above
–Click the ‘New’ button on the ‘Field maps’ related list to create 2 field maps for your start and end dates
–Select the ‘Mapping to a database field’ option from the wizard

–Map your start and end dates as shown in the images below. For the Change task table, I’ve decided to use the ‘Expected start’ field for my start date and the ‘Due date’ field my end date. You MUST use ‘dtstart’ and ‘dtend’ for the external names for iCalendar integrations.


Once you’ve got the legacy Import/Export map configured, the rest is really just a standard email notification setup. You’ll need an event trigger, an event, and a notification that responds to that event. I’m not going to go over the specifics of setting up an email notification here. You can reference the ServiceNow wiki for that.

The out-of-box Change request setup uses a section of code in the ‘change events’ business rule. Even though you can trigger an event from lots of different places in the system, I think the business rule setup is going to work the best for most scenarios. The great thing about borrowing the code from the Change request table is that it already takes care of all of the different conditions for you. All you have to do is modify the field and event names in the script to go with your custom setup. I’ve modified the below to work with the ‘Expected start’ and ‘Due date’ fields from the Change task table. I’ve also modified the script to trigger 2 new events (which you’ll need to create), called ‘change_task.calendar.notify’ and ‘change_task.calendar.notify.remove’.

‘change_task send icalendar’ business rule
Name: change_task send icalendar
Table: change_task
When: after
Insert/Update: true
Script:

if (current.expected_start.changes() || current.due_date.changes() || current.assigned_to.changes()) {
if (!current.expected_start.nil() && !current.due_date.nil() && !current.assigned_to.nil()) {
gs.eventQueue("change_task.calendar.notify", current, current.assigned_to, previous.assigned_to);
}// Remove from previous assigned to, due to assigned_to changing
if (!previous.assigned_to.nil()) {
if (!current.assigned_to.nil() && current.assigned_to.changes() &&
(!previous.expected_start.nil() && !previous.due_date.nil())) {
gs.eventQueue("change_task.calendar.notify.remove", current, current.assigned_to, previous.assigned_to);
}
}
// Remove old calendar from current assigned to, due to date changing
else if (!current.assigned_to.nil()) {
if ((current.expected_start.changes() && !previous.due_date.nil()) ||
(current.expected_start.changes() && !previous.due_date.nil())) {
gs.eventQueue("change_task.calendar.notify.remove", current, current.assigned_to, current.assigned_to);
}
}
}

Once you set up your event trigger and corresponding events, you need to set up your notifications to be triggered by those events.
The final step then (and probably the most important) is to set up your email messages or templates. Again, I’m not going to go into specifics here about how to set up an email notification. It doesn’t matter if set up your message in the notification or template, but since the out-of-box Change request iCal setup has this in email templates I’ve decided to do the same for this one for consistency. The ‘Subject’ here is strictly a label. The real subject is actually populated through the ‘Summary’ line in the body of the email.

If you’ve set up your variable mappings correctly in the steps above you shouldn’t have to customize this piece at all. Just paste the contents of each of the sections below into the ‘Message’ box on your notification or template setup, set the correct table, and go. You’ll most likely want to have 2 notifications, one for an event request and one for cancellation.

If you need a guide you can look at the ‘Notify Change Calendar’ and ‘Notify Change Calendar Remove’ Email Notifications on the ‘change_request’ table (along with their associated templates).

‘change_task.calendar.integration’ Email Templates

Calendar invite template

Name: change_task.calendar.integration
Table: change_task
Subject: SPECIAL CASE TEMPLATE — Push change tasks into an outlook calendar
Message:

BEGIN:VCALENDAR
PRODID:-//Service-now.com//Outlook 11.0
MIMEDIR//EN
VERSION:2.0
METHOD:REQUEST
BEGIN:VEVENT
ATTENDEE;ROLE=REQ-PARTICIPANT;RSVP=TRUE:MAILTO:${to}
ORGANIZER:MAILTO:${from}
DTSTART:${dtstart}
DTEND:${dtend}
LOCATION:${location}
TRANSP:OPAQUE
SEQUENCE:${sys_mod_count}
UID:${uid}
DTSTAMP:${dtstamp}
SUMMARY:${summary}
DESCRIPTION:${description}
PRIORITY:${priority}
X-MICROSOFT-CDO-IMPORTANCE:${priority}
STATUS:CONFIRMED
CLASS:PUBLIC
END:VEVENT
END:VCALENDAR

Calendar cancellation template

Name: change_task.calendar.integration.remove
Table: change_task
Subject: SPECIAL CASE TEMPLATE — Push change tasks into an outlook calendar
Message:

BEGIN:VCALENDAR
PRODID:-//Service-now.com//Outlook 11.0 MIMEDIR//EN
VERSION:2.0
METHOD:CANCEL
BEGIN:VEVENT
ATTENDEE;ROLE=REQ-PARTICIPANT;RSVP=TRUE:MAILTO:${to}
ORGANIZER:MAILTO:${from}
LOCATION:${location}
TRANSP:OPAQUE
DTSTART:${dtstart}
DTEND:${dtend}
SEQUENCE:${sys_mod_count}
UID:${uid}
DTSTAMP:${dtstamp}
DESCRIPTION:${description}
SUMMARY:${summary}
PRIORITY:${priority}
X-MICROSOFT-CDO-IMPORTANCE:${priority}
STATUS:CANCELLED
CLASS:PUBLIC
END:VEVENT
END:VCALENDAR

That’s it! If you’ve done everything correctly you should be able to send calendar invites from your change task table just like you can for change requests.

Can I send To Do Tasks or Notes too?

ServiceNow can send them if you modify the email template with the correct ‘VTODO’ or ‘VJOURNAL’ tags, but most email clients (including all from Microsoft) don’t support it. So, you can send all day, but chances are your email client won’t handle it!

The post Sending iCalendar Invites from any Task table appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/email-notifications-system-definition/sending-calendar-invites-task-table/feed/ 34
Manipulating Outbound Email in the ‘sys_email’ Table https://servicenowguru.com/email-notifications-system-definition/manipulating-outbound-email-sysemail-table/ https://servicenowguru.com/email-notifications-system-definition/manipulating-outbound-email-sysemail-table/#comments Wed, 11 Aug 2010 17:10:47 +0000 https://servicenowguru.wpengine.com/?p=1892 Here’s a cool tip that was just sent to me by my friend Jim Coyne. We collaborated to solve a problem that he had in his environment and this post shows the result he came up with. This post shows how you can manipulate records in the email log (sys_email table) when you have a

The post Manipulating Outbound Email in the ‘sys_email’ Table appeared first on ServiceNow Guru.

]]>
Here’s a cool tip that was just sent to me by my friend Jim Coyne. We collaborated to solve a problem that he had in his environment and this post shows the result he came up with. This post shows how you can manipulate records in the email log (sys_email table) when you have a need to change the contents or recipients of an email record. Manipulating the outbound email logs isn’t something that should be relied upon heavily and I would consider it basically a last resort but it can prove very helpful in solving the right type of problem.

The problem in this example was that there were emails being sent from Jim’s Service-now system that contained sensitive information. It was necessary to send this information as part of an integration with a 3rd party system but they didn’t want to retain that information in Service-now to be viewed in logs and in the activity history of task records.



The solution that we talked about was to set up a business rule on the ‘sys_email’ table to intercept these emails immediately after they were sent and parse out the sensitive information. This way, the email could be sent to the 3rd party system, but there would be no record of that sensitive information retained in Service-now. Jim then went and did the hard work and here is the business rule he ended up with…

‘sys_email’ Business Rule
The script makes sure we are looking at the proper type of email log record that we want to erase some of the contents for. The result is that any of these emails now show up in task records (indicating that they’ve been sent) but they contain no sensitive information.Name: Remove Sensitive Email Log Info.
Table: Email (sys_email)
When: Before
Insert/Update: True
Condition: current.type.changesTo(‘sent’)
Script:

var index = current.body.indexOf('Service Request Form');
if (current.recipients == 'abc@xyz.com' && index != -1 ){
current.body = 'Log information sent to 3rd party system';
current.body_text = 'Log information sent to 3rd party system';
}

The post Manipulating Outbound Email in the ‘sys_email’ Table appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/email-notifications-system-definition/manipulating-outbound-email-sysemail-table/feed/ 8
Email links using ${URI} and ${URI_REF} https://servicenowguru.com/email-notifications-system-definition/email-links-uri-uriref/ https://servicenowguru.com/email-notifications-system-definition/email-links-uri-uriref/#comments Thu, 29 Apr 2010 18:50:29 +0000 https://servicenowguru.wpengine.com/?p=1645 I learned something new today while building out a few email notifications. If you’ve been around Service-now for a while you’re probably familiar with the formatting of email notification messages. One of the common requirements for outgoing email notifications is to include a link to the originating record or task in the email. Doing this

The post Email links using ${URI} and ${URI_REF} appeared first on ServiceNow Guru.

]]>
I learned something new today while building out a few email notifications. If you’ve been around Service-now for a while
you’re probably familiar with the formatting of email notification messages. One of the common requirements for outgoing email notifications is to include a link to the originating record or task in the email. Doing this makes it easy for end users to return to the record that they need to work on. There are a couple of simple ways to include these links in the body of an email notification in Service-now. One way I’ve known about for a long time, the other way I just discovered.


The first way to add a link to a record in an outgoing email is to use the ${URI} shortcut anywhere in the body of your email notification. Using this method produces a link in your email that looks like this…

While the ${URI} method works great for most cases, you can’t do anything to modify the outgoing link. All of the links generated with this method will be formatted exactly as shown with the word ‘LINK’ in capital letters. The second method gives you an alternative to this static ‘LINK’ link.
You can invoke this shortcut by using ${URI_REF} anywhere in the body of your email notification. Using ${URI_REF} takes the display value for the linked record and uses that for the link text instead of the word ‘LINK’.

The ${URI_REF} token was introduced in the Winter 2010 Stable 1 release.

It is also possible to drill through to a related record and find the link for that record. For example, if I were sending out an email notification from an approval record and I wanted to add a link for the corresponding task to be approved, I could add it like this…
${sysapproval.URI_REF}

If neither of these ways suits your needs, it is always possible to create your own link to whatever record you need to link to. Since the email link is just HTML you just need to provide the correct URL and wrap it in the correct HTML tag. Here’s a sample function I got from the forums that takes a table name and record sys_id value as inputs and returns a formatted link based on the information provided.


var tbl = current.getTableName();
var sysID = current.sys_id;
var link = createLinkForObject(tbl,sysID);
template.print(link);
function createLinkForObject(strTableName, strSysID){
return '<a href="' + gs.getProperty('glide.servlet.uri') + gs.generateURL(strTableName, strSysID) + '">LINK TEXT HERE</a>';
}

The post Email links using ${URI} and ${URI_REF} appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/email-notifications-system-definition/email-links-uri-uriref/feed/ 28
Inbound Email – New, Reply, and Forward https://servicenowguru.com/system-definition/inbound-email-new-reply-forward/ https://servicenowguru.com/system-definition/inbound-email-new-reply-forward/#comments Mon, 12 Apr 2010 14:02:03 +0000 https://servicenowguru.wpengine.com/?p=1509 Last week i came across an issue where the system was receiving emails that we thought should have been classified as Forwarded emails and processed by a ‘Forward’ inbound email action. Even though all of the emails coming in had ‘Fw:’ as their subject prefix, some of the emails were being classified by the system

The post Inbound Email – New, Reply, and Forward appeared first on ServiceNow Guru.

]]>
Last week i came across an issue where the system was receiving emails that we thought should have been classified as Forwarded emails and processed by a ‘Forward’ inbound email action. Even though all of the emails coming in had ‘Fw:’ as their subject prefix, some of the emails were being classified by the system as ‘New’ for their receive type instead of ‘Forwarded’ as we expected. After a little more investigation we discovered that the back-end code to identify forwarded inbound email actually requires more than just ‘Fw:’ as the subject prefix. The inbound email was being classified correctly because it didn’t meet all of the criteria for a forwarded email. This article contains a summary of the classification criteria for inbound emails. It should come in handy if you’re wondering how Service-now distinguishes between New, Reply, and Forwarded emails.

New:

  • ‘New’ is the default classification for any email coming into Service-now. The system first performs all of the checks to see if an email should be classified as a ‘Reply’ or ‘Forward’ and only classifies the email as ‘New’ if none of the conditions are met.

Reply:

 

    • Subject Prefix is insignificant (The system doesn’t care if the subject starts with ‘Re:’, ‘Reply:’, or ‘Chicken:’)
    • System looks for watermark in subject and body. If a watermark is found that matches a ticket in the system, then email is classified as a ‘Reply’ receive type.
      If not found, system checks the ‘In Reply To’ header
    • Value of ‘In Reply To’ from ‘Header’ field is tested against the value of ‘Message ID’ field for a message that was sent. If a match is found, then email is classified as a ‘Reply’ receive type.
Note: Some email clients do not support ‘In Reply To’ header. In my testing GMail stripped it out, Microsoft Entourage did not. Your mileage may vary based on the email client sending the email. The bottom line here is that the system only knows about the information contained in the email log record. If it isn’t there, then it can’t be acted upon.
  • If ANY of these conditions are met, then the email is classified as a ‘Reply’ receive type and will be processed by ‘Reply’ type inbound email actions.

 

Forward:

 

  • Subject Prefix is critical
  • System looks for ‘FW:’ or ‘FWD:’ as the prefix in the subject line (Case sensitivity doesn’t matter)
    In addition, the system also looks for ‘From:’ in the body of the email. This must match exactly!
  • If BOTH of these conditions are met, then the email is classified as a ‘Forward’ receive type and will be processed by ‘Forward’ type inbound email actions.
  • Forward conditions take precedence over reply conditions

The post Inbound Email – New, Reply, and Forward appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/system-definition/inbound-email-new-reply-forward/feed/ 29
Send an Email Notification with Associated Attachments https://servicenowguru.com/scripting/send-email-notification-attachments/ https://servicenowguru.com/scripting/send-email-notification-attachments/#comments Fri, 12 Mar 2010 18:01:32 +0000 https://servicenowguru.wpengine.com/?p=1157 It’s very common to send out an email notification at different stages of a task. There are great example notifications out-of-box in the Service-now platform that show you how to set these up. In some cases, you may wish to send more than the standard information in your email. The ‘mail_script’ tag can be used

The post Send an Email Notification with Associated Attachments appeared first on ServiceNow Guru.

]]>
It’s very common to send out an email notification at different stages of a task. There are great example notifications out-of-box in the Service-now platform that show you how to set these up. In some cases, you may wish to send more than the standard information in your email. The ‘mail_script’ tag can be used to do some more advanced script processing and then print out the results using the ‘template.print’ command. Here’s a sample script that you could use in an outbound email notification. The sample script is designed to send out information about a particular task. It also includes a ‘mail_script’ function to perform some advanced processing and include links to all of the associated attachments for the task. This script can be pasted directly into the ‘Message’ field on an email notification or email template record.

Short description: ${short_description}
</br>
Click here to view: ${URI}
<hr/>
<mail_script>
attachLinks();
function attachLinks() {
   //Check for any attachments and add attachment links if they exist
   var gr = new GlideRecord('sys_attachment');
   gr.addQuery('table_sys_id',current.sys_id);
   gr.query();
   if(gr.hasNext()){
      template.print('Attachments: \n');
         while (gr.next()) {
            var attachLink = '<a href="' + gs.getProperty("glide.servlet.uri") + gs.generateURL(gr.getTableName(),gr.sys_id) +  '">' + gr.file_name + '</a>';
            template.print(attachLink +  '\n');
         }
      template.print('<hr/>');
   }
}
</mail_script>
Comments: 
${comments}
As of the June 2011 release of ServiceNow you now have the ability to actually attach a record’s attachments to an outgoing email simply by checking the ‘Include Attachments’ checkbox on the notification form. You may have to personalize the notification form to add this field.

The post Send an Email Notification with Associated Attachments appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/scripting/send-email-notification-attachments/feed/ 7
Subscribe to Multiple CIs at the Same Time in ServiceNow https://servicenowguru.com/scripting/subscribe-multiple-cis-time-servicenowcom/ https://servicenowguru.com/scripting/subscribe-multiple-cis-time-servicenowcom/#comments Fri, 08 Jan 2010 18:35:53 +0000 https://servicenowguru.wpengine.com/?p=598 A while ago I was asked by a client to help them get set up with the ServiceNow Subscription-based Notification plugin. I had previewed the functionality but really hadn’t worked with it very much. As I dug deeper I realized that the standard setup wasn’t going to work for them. Subscription-based notifications are really not

The post Subscribe to Multiple CIs at the Same Time in ServiceNow appeared first on ServiceNow Guru.

]]>
A while ago I was asked by a client to help them get set up with the ServiceNow Subscription-based Notification plugin. I had previewed the functionality but really hadn’t worked with it very much. As I dug deeper I realized that the standard setup wasn’t going to work for them. Subscription-based notifications are really not intended to be used on a bulk-subscription basis. The idea is that you might pick a handful of CIs that you are interested in and subscribe to them.

The needs that my client had brought to light the following questions:

1How can I easily subscribe to multiple CIs without having to click through the creation of a single subscription record for each CI? If I want to subscribe to the 50 network devices I’m responsible for I don’t want to have to set each of these up one-by-one.

2How can I use CI subscription notifications and not spam the end-user with a notification for each CI? An example of this would be a system administrator who is responsible for a cluster of web servers. A configuration change on one of them typically means a configuration change on all of them. We don’t want to be sending the admin an email for each of the 100 servers every time an update is made to the change ticket.

Shown below is the solution that we came up with…

Just a warning, this is some fairly advanced stuff so don’t jump in at the deep end with this unless you’ve had a chance to dip your toes in the ServiceNow administration waters already!

Question #1:How can I easily subscribe to multiple CIs without having to click through the creation of a single subscription record for each CI?
I accomplished this by creating a UI action link on the user record that redirects to record producer catalog item. The record producer collects the CI and user information, creates the subscriptions, and redirects the user to his/her subscription page.

CI Subscription Form

Multiple CI Subscription Form

1) Create a Record producer with 3 variables.
-configuration_items (list collector that references the ‘cmdb_ci’ table)
-user (reference variable that references the user table –This will be hidden by a catalog client script)
-email (single line text variable –This will be hidden by a catalog client script)

-The record producer should point to the ‘Notification Messages’ table
-The record producer should have the following in the ‘Script’ field.

var pUser = producer.user.toString();
var pEmail = producer.email.toString();
var pCIs = producer.configuration_items.toString();

//Find the user 'Primary email' notification device
var rec = new GlideRecord('cmn_notif_device');
rec.addQuery('user', pUser);
rec.addQuery('type', 'Email');
rec.addQuery('email_address', pEmail);
rec.query();
rec.next();

//Parse the list of configuration items
var list = pCIs;
var array = list.split(',');
for (var i=0; i < array.length; i++) {
//Query to see if this user has already subscribed to this CI
var nm = new GlideRecord('cmn_notif_message');
nm.addQuery('user', pUser);
nm.addQuery('configuration_item', array[i]);
nm.query();
if(!nm.next()){
//Create the CI notification records
var rec1 = new GlideRecord('cmn_notif_message');
rec1.initialize();
rec1.notification.setDisplayValue('CI affected');
rec1.user = pUser;
rec1.device = rec.sys_id;
rec1.configuration_item = array[i];
rec1.insert();
}
}

//Do not submit this record
current.setAbortAction(true);

//Add a notification message and redirect the user to the subscriptions page
gs.include('FormInfoHeader');
var fi = new FormInfoHeader();

producer.redirect = 'notification_preferences.do?sysparm_user=' + producer.user.toString() + '&sysparm_email=' + producer.email.toString();
var s = 'Subscriptions have been created.
';
s += 'You can modify the subscription settings for individual configuration items below.
';

fi.addMessage(s);

-Create an ‘onLoad’ catalog client script for your record producer with the following script. The purpose of this script is to populate the ‘user’ and ’email’ fields with data passed in from the UI action link on the user form.

function onLoad() {
//Hide the user and email fields
g_form.setDisplay('user', false);
g_form.setDisplay('email', false);

//Get parameters from url and populate them into the user and email fields
var url = document.location.toString();
var userKey = 'sysparm_user=';
var emailKey = 'sysparm_email=';
var userPosition = url.indexOf(userKey);
var emailPosition = url.indexOf(emailKey);
if (userPosition != -1){
var user = url.substr(userPosition+userKey.length, 32);
g_form.setValue('user',user);
}
if (emailPosition != -1){
var email = url.substr(emailPosition + emailKey.length);
g_form.setValue('email',email);
}
}

2) Create a ‘Form link’ UI action link on the ‘sys_user’ table that redirects to your new Record producer
-Condition: gs.getUserID() == current.sys_id || user.hasRole(‘admin’)
-Script: Note–You’ll need to put the sys_id of your record producer in here

gs.setRedirect('com.glideapp.servicecatalog_cat_item_view.do?sysparm_id=YOUR_ITEM_SYSID_HERE&sysparm_user=' + current.sys_id + '&sysparm_email=' + current.email);

Question #2:How can I use CI subscription notifications and not spam the end-user?

This can be accomplished by creating a business rule on the table of your choice (mine was on the ‘change_request’ table) with the following parameters. The business rule triggers an event that sends an email notification.

–The first thing you’ll want to do is de-activate the ‘Affected ci notifications’ business rule. This solution works separately from the trigger in that business rule.

1) Create the business rule
Name: Notify subscribers
Table: change_request (or whatever you choose)
-Runs after insert/update
Condition: current.approval.changesFrom('not requested') || current.approval.changesFrom('rejected')
-Note: I chose this condition so that the notification would only go out when approval on the change was requested. You should modify this according to your needs.
Script:

var subscribers = getSubscribers();
gs.eventQueue('task.notify.subscribers', current, gs.getUserID(), subscribers);

function getSubscribers(){
// get affected CIs
var affectedCIs = new GlideRecord('task_ci');
affectedCIs.addQuery('task',current.sys_id);
affectedCIs.query();

var allPersons = [];

while(affectedCIs.next()){
var persons = [];
allPersons = allPersons.concat(getRelatedPersons(affectedCIs.ci_item.sys_id, persons));
}

allPersons = eliminateDuplicates(allPersons);
allPersons = allPersons.toString();

return allPersons;
}

function getRelatedPersons(ci_sys_id, persons){
var relPersons = new GlideRecord('cmn_notif_message');
relPersons.addQuery('configuration_item', ci_sys_id);
relPersons.query();

while (relPersons.next()) {
persons.push(relPersons.user.sys_id.toString());
}
var rel = new GlideRecord('cmdb_rel_ci');
rel.addQuery('child', ci_sys_id);
rel.query();
while (rel.next()) {
var parentSysID = rel.parent;
// get Interested Parties for parent CIs
getRelatedPersons(parentSysID, persons);
}
return persons;
}

function eliminateDuplicates(arr) {
// remove duplicates from array
var i, len=arr.length, out=[], obj={};

for (i=0;i < len;i++) {
obj[arr[i]]=0;
}
for (i in obj) {
out.push(i);
}
return out;
}

function notifyParents(table, itemSysID) {
var rel = new GlideRecord('cmdb_rel_ci');
rel.addQuery('child', itemSysID);
rel.query();
while (rel.next()) {
var parentSysID = rel.parent;
var parentName = rel.parent.getDisplayValue();
if (!noNotify[parentSysID]) {
count ++;
gs.log('### Notifying subscribers of ' + parentName);
noNotify[parentSysID] = true;
gs.eventQueue('ci.affected', current, parentSysID, parentName);
notifyParents('cmdb_ci', parentSysID);
}
}
}

2) Register a new event in the event registry called ‘task.notify.subscribers’
3) Create a new email notification that is triggered by the ‘task.notify.subscribers’ event. I used the following parameters for my notification:
-Name: Notify CI subscribers
-Event name: task.notify.subscribers (or whatever you call your event)
-Table: change_request
-User: event.parm2
-Subject:A CI you have subscribed to is being impacted by change ${number} - ${short_description}
-Message:

${URI}
Short description: ${short_description}

Affected CIs: (Please note that the CIs listed below are only those that are directly impacted by the change request. The CI you subscribed to may be impacted as a result of impact to one or more of the CIs listed below.

var affectedCIs = new GlideRecord('task_ci');
affectedCIs.addQuery('task',current.sys_id);
affectedCIs.query();

while(affectedCIs.next()){
template.print(affectedCIs.ci_item.getDisplayValue() + '\n');
}

The post Subscribe to Multiple CIs at the Same Time in ServiceNow appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/scripting/subscribe-multiple-cis-time-servicenowcom/feed/ 6