Email notifications Archives - ServiceNow Guru https://servicenowguru.com/tag/email-notifications/ 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/tag/email-notifications/ 32 32 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
Checking for Modified or Changed Fields in Script https://servicenowguru.com/client-scripts-scripting/checking-modified-fields-script/ https://servicenowguru.com/client-scripts-scripting/checking-modified-fields-script/#comments Thu, 20 Jan 2011 13:35:43 +0000 https://servicenowguru.wpengine.com/?p=3175 Working in Service-now, you’ll find that a lot of scripting tasks come down to identifying which fields changed on a form (client-side) or record (server-side). In this post, I’ll show you some different techniques to identify changed fields in both client-side, and server-side scripts. I’ll also show you a way that you can capture changed

The post Checking for Modified or Changed Fields in Script appeared first on ServiceNow Guru.

]]>
Working in Service-now, you’ll find that a lot of scripting tasks come down to identifying which fields changed on a form (client-side) or record (server-side). In this post, I’ll show you some different techniques to identify changed fields in both client-side, and server-side scripts. I’ll also show you a way that you can capture changed fields and values and print them in an email notification…without having to check every potential field in a record.

ServiceNow - Changed Fields

Identifying modified or changed fields in Client scripts

When looking at a form in Service-now, it’s usually pretty easy to identify the fields that have changed since the form loaded (as seen in the screen shot above). The green field indicators give a simple visual cue to the user. Behind the UI, the system is taking cues as well and firing off ‘onChange’ events and setting field parameters as a result. When you write on ‘onChange’ client script or a UI policy, you can tie into the events and take actions as a result. If at all possible, you should stick to ‘onChange’ client scripts or UI policies.
There are some special situations (typically on submission of a record) where you don’t have a special event that tells you something changed. In an ‘onSubmit’ scenario, you have to check for these changes yourself. A great example of this can be used is the ‘Dirty form’ navigation property (glide.ui.dirty_form_support) that can be turned on to display a message to users if they navigate away from a ‘dirty’ or changed form without first saving the record.

Client Script examples
If you just want to do a check to see if any value on the entire form changed (a dirty form), you can use ‘g_form.modified’ in an ‘onSubmit’ client script like this…

function onSubmit() {
  if(g_form.modified){
    return confirm("Values on the form have changed.\nDo you really want to save this record?");
  }
}

If you just want to check for changes to a few specific fields then you could use something like this in an ‘onSubmit’ client script…

function onSubmit() {
  var field1 = g_form.getControl('caller_id'); //Get the 'Caller' field control
  var field2 = g_form.getControl('short_description'); //Get the 'Short description' field control
 
  //See if the 'changed' attribute on either field is true
  if(field1.changed || field2.changed){
    return confirm("Values on the form have changed.\nDo you really want to save this record?");
  }
}

Checking for changes to variables is a bit more complex because the underlying element changes names. This script will check an individual variable…

var el_id = g_form.getControl("requested_for").id;
var orig_val = gel("sys_original."+ el_id).value;
var new_val = g_form.getValue("requested_for");
if(orig_val != new_val){
   alert("It's changed");
}

This script will check for all of the variables on the form to see if they have the ‘changed’ CSS class. It will return a count, so any count greater than 0 means that something on the form has been modified…

if($$('.changed').length > 0){
   return confirm("Values on the form have changed.\nDo you really want to save this record?");
}


Identifying modified or changed fields in Business rules

Business rules are server-side scripts, so there’s no form, no green indicator, and no ‘onChange’ event to tell you what happened. In these scenarios, business rules just care about what’s on its way to the record in the database.
Service-now includes some simple convenience methods for identifying changes to a record or field in a business rule. You may have seen these used in the ‘Condition’ field on many of the out-of-box business rules. All of the methods below return true or false based on changes to the ‘current’ record.

Record change: current.changes();
Field change: current.YOUR_FIELD_NAME_HERE.changes();
Field changes TO a value: current.YOUR_FIELD_NAME_HERE.changesTo(VALUE);
Field changes FROM a value: current.YOUR_FIELD_NAME_HERE.changesFrom(VALUE);

But what if you don’t know in advance what might change? What if you just need to return a list of changed fields or values? This might be one field, or 30 fields! I recently discovered the ‘GlideScriptRecordUtil’ class can get this type of information for you. You can use the following methods in a ‘before’ or ‘after’ business rule.

var gru = GlideScriptRecordUtil.get(current);
gru.getChangedFields(); //Returns an arrayList of changed field elements with friendly names
gru.getChangedFieldNames(); //Returns an arrayList of changed field elements with database names
gru.getChanges(); //Returns an arrayList of all change values from changed fields
Business Rule example
You can paste this script into a ‘before’ business rule on any table to display information messages about changed fields. This isn’t terribly useful, but does do a good job of showing how you can process changed field results.

//Display an information message for each change to the record
var gru = GlideScriptRecordUtil.get(current);
var changedFields = gru.getChangedFields(); //Get changed fields with friendly names
var changedValues = gru.getChanges(); //Get changed field values
//Convert to JavaScript Arrays
gs.include('j2js');
changedFields = j2js(changedFields);
changedValues = j2js(changedValues);

//Process the changed fields
for(var i = 0; i < changedValues.length; i++){
   var val = changedValues[i];
   if(val.getED().getType() == -1 && val.getJournalEntry(1)){
      //Print out last journal entry for journal fields
      gs.addInfoMessage(val.getJournalEntry(1));
   }
   else{
      //Print out changed field and value for everything else
      gs.addInfoMessage(changedFields[i] + ': ' + val.getDisplayValue());
   }
}

ServiceNow Changed Fields Business Rule

Printing all record changes in an email notification

One common use case I’ve seen for collecting all record changes in an update is to send all of those changes in an email notification. Without the use of the ‘GlideScriptRecordUtil’ methods described above, this really wasn’t practical. Here’s a solution I’ve come up with that allows you to accomplish this…

The first part is gathering these changes when you trigger your email notification event. Because the changes need to be captured at the time the record is updated or inserted, this needs to happen in a business rule. This script example collects all changed fields on an incident record and passes them as an event parameter to the ‘Incident Assigned to my Group’ notification.

//Collect all changed fields
var gru = GlideScriptRecordUtil.get(current);
var fields = gru.getChangedFieldNames(); //Get changed fields with database names
//Convert to JavaScript Array
gs.include('j2js');
fields = j2js(fields);

if (!current.assignment_group.nil() && current.assignment_group.changes()) {
   gs.eventQueue("incident.assigned.to.group", current, fields , '');
}

Once you’ve passed the event (with the changed fields parameter) to your notification, you can set up a mail script to iterate through the changed fields and print the results to the outgoing email.

One thing you’ll want to be careful of here is read access to the fields and values you’re printing out. There’s not a simple way to determine who should be able to read these fields in an email notification so if you’re sending an email to end users, you probably want to specify individual fields in a more targeted technique.
Changed fields:
<mail_script>
//Process the changed fields
var fields = event.parm1.split(',');
for(x in fields){
   //Get the field label, value, and type
   var field = fields[x];
   var fieldLabel = eval('current.' + field + '.getLabel()');
   var fieldVal = eval('current.' + field+ '.getDisplayValue()');
   var fieldType = eval('current.' + field + '.getED().getType()');

   if(fieldType == -1 && eval('current.' + field + '.getJournalEntry(1)')){
      //Print out last journal entry for journal fields
      template.print(eval('current.' + field + '.getJournalEntry(1)'));
   }
   else{
      //Print out changed field and value for everything else
      template.print(fieldLabel + ': ' + fieldVal + '\n');
   }
}
</mail_script>

The result of this mail script will look something like this…
Email Changed Fields

The post Checking for Modified or Changed Fields in Script appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/client-scripts-scripting/checking-modified-fields-script/feed/ 40
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
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