This article is a supplement to the ServiceNow documentation. For full documentation please refer ServiceNow official website
Checkout our NEW Video Channel you can like and subscribe too!

Use case

Customer wants an excel as a attachment in the mail with the list of all users in SNOW who are using the below Dashboards at what time.

  • Test-DB
  • Test-Backup

scheduledjob190120216.JPG

Solution

To achive this we will create a scheduled job

  1. Navigate to System Defination > scheduled job scheduledjob190120211.JPG

  2. Click on New Button scheduledjob190120212.JPG

  3. Select “Automatically run a script your choosing

scheduledjob190120213.JPG

  1. Fillup fileds as required. scheduledjob190120214.JPG

scheduledjob190120215.JPG

 var SUBJECT = "Dashboards Reports";
var RECIPENTS = ["c.mukherjee88@gmail.com"];
//var EMAIL_BODY = "Please note that this mail is for users information in SNOW who are all using the below Dahsboards :Test-DB ; Test-Backup";
var REPORT_COLUMNS = ["Dashboard Name", "Viewer", "Time(UTC)"];
var CSV_NAME = "Dashboard Details.csv";
//var DASHBOARD_VIEW = "CMDB Dashboard - CMDB View";
var DASHBOARD_VIEW = ["Test-DB", "Test- Backup"];
var EMAIL_BODY = "Please find Dashboard Usage information for " + DASHBOARD_VIEW.toString();

//Inserting record in sys_email table
var mailGr = new GlideRecord('sys_email');
mailGr.initialize();
mailGr.type = 'send-ignored';
mailGr.notification_type = 'SMTP';
mailGr.subject = SUBJECT;
mailGr.recipients = RECIPENTS.toString();
mailGr.body = '<html><head></head><body>' + EMAIL_BODY + '<div>&nbsp;</div><div style="display:inline">PFA the csv.</div></body></html>';
mailGr.content_type = 'multipart/mixed';
mailGr.insert();

var csvData = REPORT_COLUMNS.toString() + "\r\n";
var content = '';

//Extracting data from Navigator history table
var gr = new GlideRecord('sys_ui_navigator_history');
gr.addEncodedQuery("descriptionIN" + DASHBOARD_VIEW.toString() + "^sys_created_onONLast 60 days@javascript:gs.beginningOfLast60Days()@javascript:gs.endOfLast60Days()^title=Dashboard");
gr.query();
while (gr.next()) {
    content = '';
    content = content + gr.description + ",";
    content = content + gr.user.getDisplayValue() + ",";
    content = content + gr.sys_created_on + "\r\n";
    gs.print(content);
    csvData = csvData + content;
}

//Inserting in sys_attachement table of mailgr record.
var sa = new GlideSysAttachment();
sa.write(mailGr, CSV_NAME, 'application/csv', csvData);

var attachmentget = new GlideSysAttachment();
var agr = attachmentget.getAttachments('sys_email', mailGr.sys_id);
if (agr.next()) {
    var sysEmailAttachment = new GlideRecord('sys_email_attachment');
    sysEmailAttachment.initialize();
    sysEmailAttachment.attachment = agr.sys_id;
    sysEmailAttachment.file_name = agr.file_name.toString();
    sysEmailAttachment.source = 'notification';
    sysEmailAttachment.content_disposition = 'attachment';
    sysEmailAttachment.email = mailGr.sys_id;
    sysEmailAttachment.insert();
}

mailGr.type = 'send-ready';
mailGr.update();

Then RECIPENTS(c.mukherjee88@gmail.com) will receive a mail with an excel with below details:

scheduledjob190120216.JPG

## Another example ( youtube video source code)

Email Attachment

//This will be email Subject
var SUBJECT = "Monthly Reports";

//Recipent list
var RECIPENTS = ["learnnowlab@gmail.com"];

//Mention report columns here
var REPORT_COLUMNS = ["Incident Number", "Short Description", "Assigned To"];

//Name of the CSV
var CSV_NAME = "Incident Tracker.csv";

//Email body static content
var EMAIL_BODY = "Please find attached Incident updated this month";

//Instance URL
var instanceURL = gs.getProperty('glide.servlet.uri');

//SRAPI URL that we will create in later half of this video
var restAPIEndpoint = "api/196834/download_link/reports";
var downloadLink = instanceURL + restAPIEndpoint;

//Inserting record in sys_email table
var mailGr = new GlideRecord('sys_email');
mailGr.initialize();

//email should be send when we are ready.let us pause in the queue
mailGr.type = 'send-ignored';
mailGr.notification_type = 'SMTP';
mailGr.subject = SUBJECT;
mailGr.recipients = RECIPENTS.toString();
mailGr.content_type = 'multipart/mixed';
mailGr.insert();

var csvData = REPORT_COLUMNS.toString() + "\r\n";
var content = '';

//Extracting data from Incident table
var gr = new GlideRecord('incident');
gr.addEncodedQuery("sys_updated_onONThis month@javascript:gs.beginningOfThisMonth()@javascript:gs.endOfThisMonth()");
gr.query();
while (gr.next()) {
    content = '';
    content = content + gr.number + ",";
    content = content + gr.short_description + ",";

    //The new line is important it should be added on the last column value
    content = content + gr.assigned_to.getDisplayValue() + "\r\n";

    csvData = csvData + content;
}

//Inserting in sys_attachement table of mailgr record.
var sa = new GlideSysAttachment();
sa.write(mailGr, CSV_NAME, 'application/csv', csvData);

var attachmentget = new GlideSysAttachment();
var agr = attachmentget.getAttachments('sys_email', mailGr.sys_id);
if (agr.next()) {

    //Additionally we have to link the mailgr with an entry in sys_email_attachment
    var sysEmailAttachment = new GlideRecord('sys_email_attachment');
    sysEmailAttachment.initialize();
    sysEmailAttachment.attachment = agr.sys_id;
    sysEmailAttachment.file_name = agr.file_name.toString();
    sysEmailAttachment.source = 'notification';
    sysEmailAttachment.content_disposition = 'attachment';
    sysEmailAttachment.email = mailGr.sys_id;
    sysEmailAttachment.insert();

    //construct download link ( will be used when user click on downlink in email)
    downloadLink = downloadLink + "/" + agr.sys_id;
}

//construct email body
mailGr.body = '<html><head></head><body>' + EMAIL_BODY + 'Optionally you can download also from this <a href="'+downloadLink+'">link</a></body></html>';

//All ok now tag email as ready so that notification queue picks up and send email
mailGr.type = 'send-ready';

mailGr.update();

Scripted restApi

(function process( /*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {

    //Extract the sysid of the attachment from the request url
    var attachment_sys_id = request.pathParams.sys_id + '';
	
    //Construct headers
    var hdrs = {};
    hdrs['Content-Type'] = 'application/octet-stream';

    //Get filename from attachment table.This will be the name that user will see when link is clicked
    var gr = new GlideRecord('sys_attachment');
    gr.addQuery('sys_id', attachment_sys_id);
    gr.query();
    if (gr.next()) {
        hdrs['Content-Disposition'] = 'attachment;filename=' + gr.file_name;
    }
    response.setStatus(200);
    response.setHeaders(hdrs);

    //write the content as output stream
    var writer = response.getStreamWriter();
    var attachmentStream = new GlideSysAttachmentInputStream(attachment_sys_id);
    writer.writeStream(attachmentStream);

})(request, response);
    Content