Copy attachments to RITM record created through inbound action

prasannasun
Tera Contributor

Hi Team,

 

I have created an onbound action in sc_request table and itis creating the RITM catalog item and I have to copy the attachments records which are given in email to RITm but it is not happening. Can someone help me with this if there is anything wrong here in script or is there any way that I can use to copy the attachments which are coming through inbound actions to RITm record

 

here is the script that I have written everything is working s expected but the ttachments are not copying to RITm from emails.

 

(function runAction( /*GlideRecord*/ current, /*GlideRecord*/ event, /*EmailWrapper*/ email, /*ScopedEmailLogger*/ logger, /*EmailClassifier*/ classifier) {

    // Check for the sender's email and ensure it matches the specified ones
 
        var cartId = GlideGuid.generate(null);
        var cart = new Cart(cartId);

        // Add your requested item to the cart using sys_id of the catalog item
        var item = cart.addItem('HERE ITEM SYS-ID', 1);
        cart.setVariable(item, "short_description", email.body.company + ' Request Access for ' + email.body.an_offer_has_been_extended_to_the_following_candidate);
        cart.setVariable(item, "description", email.body_text);
        cart.setVariable(item, "entity", email.body.company);
        cart.setVariable(item, "supervisor", email.body.supervisor);
        cart.setVariable(item, "phone_number", 'XXX-XXX-XXXX');
        cart.setVariable(item, "department", email.body.department);
       

        var reqTitleMatch = email.body_text.match(/Req\s*-\s*Title:\s*(.+)/i);
        var reqTitle = reqTitleMatch ? reqTitleMatch[1].trim() : "";
        cart.setVariable(item, "title", reqTitle);

        // Extract the date for 'needed_by' from the email body
        var emailBody = email.body_text;
        var dateRegex = /Preliminary Start Date:\s*([A-Za-z]+\s+\d{1,2},\s+\d{4})/;
        var match = dateRegex.exec(emailBody);

        if (match) {
            var preliminaryStartDate = match[1]; // e.g., "January 15, 2025"

            // Parse the date to "yyyy-MM-dd" format
            var dateParts = preliminaryStartDate.match(/([A-Za-z]+)\s+(\d{1,2}),\s+(\d{4})/);
            if (dateParts) {
                var monthName = dateParts[1];
                var day = dateParts[2];
                var year = dateParts[3];

                var monthMap = {
                    January: "01", February: "02", March: "03", April: "04",
                    May: "05", June: "06", July: "07", August: "08",
                    September: "09", October: "10", November: "11", December: "12"
                };

                var month = monthMap[monthName];
                var formattedDate = year + "-" + month + "-" + (day.length === 1 ? "0" + day : day);
                cart.setVariable(item, "needed_by", formattedDate);
            }
        }

        // Place the order
        var rc = cart.placeOrder();
        gs.info('Inbound email processed, order placed: ' + rc.number + ' ' + email.body_text);
       
        var ritmGR = new GlideRecord('sc_req_item');
        ritmGR.addQuery('request', rc.sys_id);
        ritmGR.query();
        while (ritmGR.next()) {
            GlideSysAttachment.copy('sys_email', email.sys_id, 'sc_req_item', ritmGR.sys_id);
            gs.info('Attachments copied from email ' + email.sys_id + ' to RITM ' + ritmGR.number);
        }
})(current, event, email, logger, classifier);
    
1 ACCEPTED SOLUTION

Ankur Bawiskar
Tera Patron
Tera Patron

@prasannasun 

update your line with this and test once

           new GlideSysAttachment().copy('sys_email', sys_email.sys_id, 'sc_req_item', ritmGR.sys_id);

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

View solution in original post

5 REPLIES 5

Nawal Singh
Tera Guru

Hi  @prasannasun ,

 

Why Your Current Code Isn't Copying Attachments

GlideSysAttachment.copy('sys_email', email.sys_id, 'sc_req_item', ritmGR.sys_id) is running too early.

In an inbound email action, the email’s attachments are still being processed asynchronously, so your script runs before the attachments exist on the sys_email record.

 

 

Updated Inbound Email Action Script:

 

 

(function runAction( /*GlideRecord*/ current, /*GlideRecord*/ event, /*EmailWrapper*/ email, /*ScopedEmailLogger*/ logger, /*EmailClassifier*/ classifier) { var cartId = GlideGuid.generate(null); var cart = new Cart(cartId); // Add your requested item to the cart using sys_id of the catalog item var item = cart.addItem('YOUR-CATALOG-ITEM-SYS-ID', 1); cart.setVariable(item, "short_description", email.body.company + ' Request Access for ' + email.body.an_offer_has_been_extended_to_the_following_candidate); cart.setVariable(item, "description", email.body_text); cart.setVariable(item, "entity", email.body.company); cart.setVariable(item, "supervisor", email.body.supervisor); cart.setVariable(item, "phone_number", 'XXX-XXX-XXXX'); cart.setVariable(item, "department", email.body.department); // Parse "Req - Title:" var reqTitleMatch = email.body_text.match(/Req\s*-\s*Title:\s*(.+)/i); var reqTitle = reqTitleMatch ? reqTitleMatch[1].trim() : ""; cart.setVariable(item, "title", reqTitle); // Parse "Preliminary Start Date:" var emailBody = email.body_text; var dateRegex = /Preliminary Start Date:\s*([A-Za-z]+\s+\d{1,2},\s+\d{4})/; var match = dateRegex.exec(emailBody); if (match) { var preliminaryStartDate = match[1]; var dateParts = preliminaryStartDate.match(/([A-Za-z]+)\s+(\d{1,2}),\s+(\d{4})/); if (dateParts) { var monthMap = { January: "01", February: "02", March: "03", April: "04", May: "05", June: "06", July: "07", August: "08", September: "09", October: "10", November: "11", December: "12" }; var month = monthMap[dateParts[1]]; var day = dateParts[2].padStart(2, '0'); var year = dateParts[3]; var formattedDate = `${year}-${month}-${day}`; cart.setVariable(item, "needed_by", formattedDate); } } // Place the order var rc = cart.placeOrder(); gs.info('Inbound email processed, order placed: ' + rc.number); // Find the RITM and raise an event to copy attachments var ritmGR = new GlideRecord('sc_req_item'); ritmGR.addQuery('request', rc.sys_id); ritmGR.query(); while (ritmGR.next()) { gs.eventQueue('custom.copy.email.attachments', ritmGR, email.sys_id, ritmGR.sys_id); gs.info('Event triggered to copy attachments for RITM: ' + ritmGR.number); } })(current, event, email, logger, classifier);

Now Create a Script Action

Go to System Policy > Events > Script Actions, and create one:

Name: Copy Email Attachments to RITM

Event Name: custom.copy.email.attachments

Table: sc_req_item (or leave blank)

Active: true

Script:

(function executeRule(current, event, email, email_action, event_parm1, event_parm2, log, gs) {
var emailSysId = event_parm1; // sys_email
var ritmSysId = event_parm2; // sc_req_item

if (!emailSysId || !ritmSysId) {
gs.error("Missing email or RITM sys_id for attachment copy.");
return;
}

// Optional: Wait 3 seconds to ensure attachments are committed
gs.sleep(3000);

var ritmGR = new GlideRecord('sc_req_item');
if (ritmGR.get(ritmSysId)) {
GlideSysAttachment.copy('sys_email', emailSysId, 'sc_req_item', ritmSysId);
gs.info(" Attachments copied from sys_email:" + emailSysId + " to RITM: " + ritmGR.number);
} else {
gs.error(" Failed to find RITM with sys_id: " + ritmSysId);
}
})(current, event, email, email_action, event.parm1, event.parm2, log, gs);

 

 

If this resolved your issue, kindly mark it as the accepted solution to help others who may encounter the same problem

Regards,
Nawal Singh