How to send attachment from one servicenow to another?

SandeepKSingh
Kilo Sage

Hi Team,

I have one requirnment to share an Incident details created on one servicenow instance that should create on another servicenow instance.


Any sample code ??

 

 

Thanks

Snow Learner

3 ACCEPTED SOLUTIONS

Dr Atul G- LNG
Tera Patron
Tera Patron

Hi @SandeepKSingh 

https://www.servicenow.com/community/developer-forum/transfer-attachment-from-one-to-another-instanc...

 

https://www.servicenow.com/community/developer-forum/how-to-send-attachment-from-one-instance-to-oth...

*************************************************************************************************************
If my response proves useful, please indicate its helpfulness by selecting " Accept as Solution" and " Helpful." This action benefits both the community and me.

Regards
Dr. Atul G. - Learn N Grow Together
ServiceNow Techno - Functional Trainer
LinkedIn: https://www.linkedin.com/in/dratulgrover
YouTube: https://www.youtube.com/@LearnNGrowTogetherwithAtulG
Topmate: https://topmate.io/atul_grover_lng [ Connect for 1-1 Session]

****************************************************************************************************************

View solution in original post

Ravi Gaurav
Giga Sage
Giga Sage

Hi,

you can use Business Rule (async BR on Insert or update based on your requirnment).

Assuming async BR--> on Insert:-

(function executeRule(current, previous /*null when async*/ ) {
    var answer = "";
    var attachmentMsg = "";
    var targetUserID = "admin";
    var targetUserPassword = "giveYourPassword";
    var targetInstanceURL = "https://dev244808.service-now.com/";

    // Update Incident
    var r = new sn_ws.RESTMessageV2('dev244808-Ebonding', 'Update-New');
    r.setStringParameterNoEscape('sys_id', current.sys_id);
    var response = r.execute();
    var responseBody = response.getBody();
    var httpStatus = response.getStatusCode();
    gs.addInfoMessage("Update-New response status: " + httpStatus);

    if (httpStatus.toString() == "200") {
        answer = "Incident successfully sent.";

        // Check for Existing Attachments
        var checkIncident = new sn_ws.RESTMessageV2('dev244808-Ebonding', 'Get Attachment');
        checkIncident.setStringParameterNoEscape('sys_id', current.sys_id);
        var checkResponse = checkIncident.execute();
        var checkResponseBody = checkResponse.getBody();
        var checkHttpStatus = checkResponse.getStatusCode();
        gs.addInfoMessage("Get Attachment response status: " + checkHttpStatus);
        var existingAttachments = JSON.parse(checkResponseBody).result;
        var existingAttachmentNames = [];

        for (var i = 0; i < existingAttachments.length; i++) {
            if (existingAttachments[i].table_sys_id == current.sys_id.toString()) {
                existingAttachmentNames.push(existingAttachments[i].file_name);
            }
        }

        gs.addInfoMessage(existingAttachmentNames.length + " matching attachment(s) found: table_sys_id matches current.sys_id");

        // Send New Attachments
        var parser = new JSONParser();
        var parsed = parser.parse(responseBody);
        var targetRec = parsed.result;
        var attachmentCount = sendAttachments(current.getTableName(), current.sys_id, targetRec.sys_id, existingAttachmentNames);
        if (attachmentCount.length > 0) {
            attachmentMsg = " Attachments successfully sent: " + attachmentCount[0] + ". Attachments failed to be sent: " + attachmentCount[1];
        } else {
            attachmentMsg = " Record had no new attachments to send.";
        }
    } else {
        gs.addInfoMessage('Failed');
    }

    answer += " " + attachmentMsg;
    gs.addInfoMessage(answer);

    function sendAttachments(sourceTable, sourceID, targetID, existingAttachmentNames) {
        var answer = [0, 0]; // successful attachments, failed attachments
        var attachmentRec = new GlideRecord("sys_attachment");
        attachmentRec.addQuery("table_sys_id", sourceID);
        attachmentRec.addQuery("table_name", sourceTable);
        attachmentRec.query();

        while (attachmentRec.next()) {
            var fileName = attachmentRec.file_name.toString();
            gs.addInfoMessage("Processing attachment: " + fileName);
            if (existingAttachmentNames.indexOf(fileName) === -1) {
                gs.addInfoMessage("Sending new attachment: " + fileName);
                var attachmentMessage = new sn_ws.RESTMessageV2();
                attachmentMessage.setHttpMethod("post");
                attachmentMessage.setBasicAuth(targetUserID, targetUserPassword);
                attachmentMessage.setEndpoint(targetInstanceURL + "api/now/attachment/file");
                attachmentMessage.setQueryParameter("table_name", sourceTable);
                attachmentMessage.setQueryParameter("table_sys_id", targetID);
                attachmentMessage.setQueryParameter("file_name", fileName);
                attachmentMessage.setRequestHeader("Content-Type", attachmentRec.content_type);
                attachmentMessage.setRequestHeader("Accept", "application/json");
                attachmentMessage.setRequestBodyFromAttachment(attachmentRec.sys_id);
                var response = attachmentMessage.execute();
                var httpStatus = response.getStatusCode();
                gs.addInfoMessage("Attachment response status: " + httpStatus);
                if (httpStatus.toString() == "201") {
                    answer[0] += 1;
                } else {
                    answer[1] += 1;
                }
            } else {
                gs.addInfoMessage("Attachment already exists: " + fileName);
            }
        }
        return answer;
    }
})(current, previous);
 
 




--------------------------------------------------------------------------------------------------------------------------


If you found my response helpful, I would greatly appreciate it if you could mark it as "Accepted Solution" and "Helpful."
Your support not only benefits the community but also encourages me to continue assisting. Thank you so much!

Thanks and Regards
Ravi Gaurav | ServiceNow MVP 2025,2024 | ServiceNow Practice Lead | Solution Architect
CGI
M.Tech in Data Science & AI

 YouTube: https://www.youtube.com/@learnservicenowwithravi
 LinkedIn: https://www.linkedin.com/in/ravi-gaurav-a67542aa/

View solution in original post

Ravi Gaurav
Giga Sage
Giga Sage

Can you try the below also :-- 

 

// Set the REST endpoint URL
var restEndpoint = "https://XXXXX.service-now.com/api/now/table/incident?sysparm_query=&sysparm_display_value=false&sysp..." + limit + "&sysparm_offset=" + offset;

// Set the authentication profile
var r = new sn_ws.RESTMessageV2();
r.setEndpoint(restEndpoint);
r.setHttpMethod('GET');
r.setRequestHeader('Content-Type', 'application/json');
r.setAuthenticationProfile('basic', "c8ac221adb1209900034150505961988"); // create your own basic profile

// Execute the REST API call
try {
var response = r.execute();
} catch(e) {
gs.log("ERROR: Sending REST API " + e + "\n\n" + restEndpoint, "DATA_MIGRATION_LOG");
}

// Parse the response
if (!response.haveError()) {
var parsed = JSON.parse(response.getBody());
var results = parsed.result;

// Loop through the results and create a new Incident on the target instance
results.forEach(function(item) {
var gr = new GlideRecord('incident');
gr.initialize();

// Set the Incident fields
for (var key in item) {
if (key == "sys_id") {
gr.setNewGuidValue(item[key]);
} else if (key != "sys_tags") {
gr.setValue(key, item[key]);
}
}

// Insert the new Incident
gr.autoSysFields(false);
gr.setWorkflow(false);
var recordSysId = gr.insert();

// Log any errors
if (!recordSysId) {
gs.log("NOT INSERTED: incident." + item.sys_id + " : " + gr.getLastErrorMessage(), "DATA_MIGRATION_LOG");
}
});
} else {
var responseBody = response.getBody();
var message = responseBody + "\nStatus Code: " + response.getStatusCode() + "\nError Code: " + response.getErrorCode() + "\nError Message: " + response.getErrorMessage();
gs.log("ERROR: responce REST API " + restEndpoint + "\n\n" + message, "DATA_MIGRATION_LOG");
}

--------------------------------------------------------------------------------------------------------------------------


If you found my response helpful, I would greatly appreciate it if you could mark it as "Accepted Solution" and "Helpful."
Your support not only benefits the community but also encourages me to continue assisting. Thank you so much!

Thanks and Regards
Ravi Gaurav | ServiceNow MVP 2025,2024 | ServiceNow Practice Lead | Solution Architect
CGI
M.Tech in Data Science & AI

 YouTube: https://www.youtube.com/@learnservicenowwithravi
 LinkedIn: https://www.linkedin.com/in/ravi-gaurav-a67542aa/

View solution in original post

3 REPLIES 3

Dr Atul G- LNG
Tera Patron
Tera Patron

Hi @SandeepKSingh 

https://www.servicenow.com/community/developer-forum/transfer-attachment-from-one-to-another-instanc...

 

https://www.servicenow.com/community/developer-forum/how-to-send-attachment-from-one-instance-to-oth...

*************************************************************************************************************
If my response proves useful, please indicate its helpfulness by selecting " Accept as Solution" and " Helpful." This action benefits both the community and me.

Regards
Dr. Atul G. - Learn N Grow Together
ServiceNow Techno - Functional Trainer
LinkedIn: https://www.linkedin.com/in/dratulgrover
YouTube: https://www.youtube.com/@LearnNGrowTogetherwithAtulG
Topmate: https://topmate.io/atul_grover_lng [ Connect for 1-1 Session]

****************************************************************************************************************

Ravi Gaurav
Giga Sage
Giga Sage

Hi,

you can use Business Rule (async BR on Insert or update based on your requirnment).

Assuming async BR--> on Insert:-

(function executeRule(current, previous /*null when async*/ ) {
    var answer = "";
    var attachmentMsg = "";
    var targetUserID = "admin";
    var targetUserPassword = "giveYourPassword";
    var targetInstanceURL = "https://dev244808.service-now.com/";

    // Update Incident
    var r = new sn_ws.RESTMessageV2('dev244808-Ebonding', 'Update-New');
    r.setStringParameterNoEscape('sys_id', current.sys_id);
    var response = r.execute();
    var responseBody = response.getBody();
    var httpStatus = response.getStatusCode();
    gs.addInfoMessage("Update-New response status: " + httpStatus);

    if (httpStatus.toString() == "200") {
        answer = "Incident successfully sent.";

        // Check for Existing Attachments
        var checkIncident = new sn_ws.RESTMessageV2('dev244808-Ebonding', 'Get Attachment');
        checkIncident.setStringParameterNoEscape('sys_id', current.sys_id);
        var checkResponse = checkIncident.execute();
        var checkResponseBody = checkResponse.getBody();
        var checkHttpStatus = checkResponse.getStatusCode();
        gs.addInfoMessage("Get Attachment response status: " + checkHttpStatus);
        var existingAttachments = JSON.parse(checkResponseBody).result;
        var existingAttachmentNames = [];

        for (var i = 0; i < existingAttachments.length; i++) {
            if (existingAttachments[i].table_sys_id == current.sys_id.toString()) {
                existingAttachmentNames.push(existingAttachments[i].file_name);
            }
        }

        gs.addInfoMessage(existingAttachmentNames.length + " matching attachment(s) found: table_sys_id matches current.sys_id");

        // Send New Attachments
        var parser = new JSONParser();
        var parsed = parser.parse(responseBody);
        var targetRec = parsed.result;
        var attachmentCount = sendAttachments(current.getTableName(), current.sys_id, targetRec.sys_id, existingAttachmentNames);
        if (attachmentCount.length > 0) {
            attachmentMsg = " Attachments successfully sent: " + attachmentCount[0] + ". Attachments failed to be sent: " + attachmentCount[1];
        } else {
            attachmentMsg = " Record had no new attachments to send.";
        }
    } else {
        gs.addInfoMessage('Failed');
    }

    answer += " " + attachmentMsg;
    gs.addInfoMessage(answer);

    function sendAttachments(sourceTable, sourceID, targetID, existingAttachmentNames) {
        var answer = [0, 0]; // successful attachments, failed attachments
        var attachmentRec = new GlideRecord("sys_attachment");
        attachmentRec.addQuery("table_sys_id", sourceID);
        attachmentRec.addQuery("table_name", sourceTable);
        attachmentRec.query();

        while (attachmentRec.next()) {
            var fileName = attachmentRec.file_name.toString();
            gs.addInfoMessage("Processing attachment: " + fileName);
            if (existingAttachmentNames.indexOf(fileName) === -1) {
                gs.addInfoMessage("Sending new attachment: " + fileName);
                var attachmentMessage = new sn_ws.RESTMessageV2();
                attachmentMessage.setHttpMethod("post");
                attachmentMessage.setBasicAuth(targetUserID, targetUserPassword);
                attachmentMessage.setEndpoint(targetInstanceURL + "api/now/attachment/file");
                attachmentMessage.setQueryParameter("table_name", sourceTable);
                attachmentMessage.setQueryParameter("table_sys_id", targetID);
                attachmentMessage.setQueryParameter("file_name", fileName);
                attachmentMessage.setRequestHeader("Content-Type", attachmentRec.content_type);
                attachmentMessage.setRequestHeader("Accept", "application/json");
                attachmentMessage.setRequestBodyFromAttachment(attachmentRec.sys_id);
                var response = attachmentMessage.execute();
                var httpStatus = response.getStatusCode();
                gs.addInfoMessage("Attachment response status: " + httpStatus);
                if (httpStatus.toString() == "201") {
                    answer[0] += 1;
                } else {
                    answer[1] += 1;
                }
            } else {
                gs.addInfoMessage("Attachment already exists: " + fileName);
            }
        }
        return answer;
    }
})(current, previous);
 
 




--------------------------------------------------------------------------------------------------------------------------


If you found my response helpful, I would greatly appreciate it if you could mark it as "Accepted Solution" and "Helpful."
Your support not only benefits the community but also encourages me to continue assisting. Thank you so much!

Thanks and Regards
Ravi Gaurav | ServiceNow MVP 2025,2024 | ServiceNow Practice Lead | Solution Architect
CGI
M.Tech in Data Science & AI

 YouTube: https://www.youtube.com/@learnservicenowwithravi
 LinkedIn: https://www.linkedin.com/in/ravi-gaurav-a67542aa/

Ravi Gaurav
Giga Sage
Giga Sage

Can you try the below also :-- 

 

// Set the REST endpoint URL
var restEndpoint = "https://XXXXX.service-now.com/api/now/table/incident?sysparm_query=&sysparm_display_value=false&sysp..." + limit + "&sysparm_offset=" + offset;

// Set the authentication profile
var r = new sn_ws.RESTMessageV2();
r.setEndpoint(restEndpoint);
r.setHttpMethod('GET');
r.setRequestHeader('Content-Type', 'application/json');
r.setAuthenticationProfile('basic', "c8ac221adb1209900034150505961988"); // create your own basic profile

// Execute the REST API call
try {
var response = r.execute();
} catch(e) {
gs.log("ERROR: Sending REST API " + e + "\n\n" + restEndpoint, "DATA_MIGRATION_LOG");
}

// Parse the response
if (!response.haveError()) {
var parsed = JSON.parse(response.getBody());
var results = parsed.result;

// Loop through the results and create a new Incident on the target instance
results.forEach(function(item) {
var gr = new GlideRecord('incident');
gr.initialize();

// Set the Incident fields
for (var key in item) {
if (key == "sys_id") {
gr.setNewGuidValue(item[key]);
} else if (key != "sys_tags") {
gr.setValue(key, item[key]);
}
}

// Insert the new Incident
gr.autoSysFields(false);
gr.setWorkflow(false);
var recordSysId = gr.insert();

// Log any errors
if (!recordSysId) {
gs.log("NOT INSERTED: incident." + item.sys_id + " : " + gr.getLastErrorMessage(), "DATA_MIGRATION_LOG");
}
});
} else {
var responseBody = response.getBody();
var message = responseBody + "\nStatus Code: " + response.getStatusCode() + "\nError Code: " + response.getErrorCode() + "\nError Message: " + response.getErrorMessage();
gs.log("ERROR: responce REST API " + restEndpoint + "\n\n" + message, "DATA_MIGRATION_LOG");
}

--------------------------------------------------------------------------------------------------------------------------


If you found my response helpful, I would greatly appreciate it if you could mark it as "Accepted Solution" and "Helpful."
Your support not only benefits the community but also encourages me to continue assisting. Thank you so much!

Thanks and Regards
Ravi Gaurav | ServiceNow MVP 2025,2024 | ServiceNow Practice Lead | Solution Architect
CGI
M.Tech in Data Science & AI

 YouTube: https://www.youtube.com/@learnservicenowwithravi
 LinkedIn: https://www.linkedin.com/in/ravi-gaurav-a67542aa/