Inbound Action Script Issue

Mustafa4
Tera Contributor

Hi Community Helpers,

I am creating a request through an Inbound Action script using the XML and script provided below. However, I am facing an issue when the email body contains hyperlinks or when the sender’s email includes a signature. In such cases, the request is not being generated.

When the email body contains only plain text, the request is created successfully.

Could you please review my attached script and help identify where I might be going wrong? I would appreciate any corrections or improvements to make the script work in all scenarios.

Thanks in advance!

Inbound Action Script :

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

    // Implement email action here


    var senderEmail = email.from;
    //  gs.info("Mustafa Sender Email: " + senderEmail);
    // gs.info('Test Mustafa@1');
    var emailBody = email.body_text;
    var SnUser = gs.getProperty("ag.sys_user.xml_integration_user.sys_id");


    var xmlStart = emailBody.indexOf('<?xml');
    if (xmlStart == -1) {
        gs.error('SuccessFactors Email: No XML found in email body');
        return;
    }
    emailBody = emailBody.substring(xmlStart);
    emailBody = emailBody.replace(/<mailto:[^>]*>/g, '');
    emailBody = emailBody.replace(/\[mailto:[^\]]*\]/g, '');
    // gs.info('Test Mustafa@EB' + emailBody);
    var j = gs.xmlToJSON(emailBody);

    if (!j || !j.SuccessFactorsRequest) {
        gs.error('SuccessFactors Email: XML parsing failed or missing root element');
        return;
    }

    var a = JSON.stringify(j);
    // gs.info('Test Mustafa@A' + a);
    var summary = j.SuccessFactorsRequest.Summary.toString();
    var description = j.SuccessFactorsRequest.DetailDescription.toString();
    var requestedForEmail = j.SuccessFactorsRequest.RequestedFor.toString();
    var priorityText = j.SuccessFactorsRequest.RequestPriority.toString();

    // Create request via Cart
    // gs.info('Test Mustafa@Email' + requestedForEmail);
    var cart = new Cart();
    var item = cart.addItem('906a49bc1b0ee110e533759d1e4bcbc1');
   
    cart.setVariable(item, 'summary', summary);
    cart.setVariable(item, 'detail_description', description);
    //cart.setVariable(item, 'requested_for', SnUser);
    cart.setVariable(item, 'requested_by',  SnUser);
    cart.setVariable(item, 'request_priority', priorityText);
    var requestId = cart.placeOrder();
    var req = requestId.number.toString();
    // gs.info('Test Mustafa@3' + req);
    // Update opened_by for request and RITM
    var reqGR = new GlideRecord('sc_request');
    reqGR.addQuery('number', req);
    reqGR.query();
    if (reqGR.next()) {
        reqGR.opened_by = SnUser;

        if (requestedForEmail != '') {
            var gr = new GlideRecord("sys_user");
            gr.addQuery('email', requestedForEmail);
            gr.query();
            if (gr.next())
                reqGR.requested_for = gr.sys_id;

        } else if (email.from == "ifguestuser@email.com") {

            reqGR.requested_for = SnUser;
        }
        reqGR.update();
        var ritm = new GlideRecord('sc_req_item');
        ritm.addQuery('request.number', req);
        ritm.query();
        if (ritm.next()) {
            ritm.opened_by = SnUser;

            //  gs.info('Mustafa@SN1' + requestedForEmail);
            if (requestedForEmail != '') {
                var gr = new GlideRecord("sys_user");
                gr.addQuery('email', requestedForEmail);
                gr.query();
                if (gr.next())
                    // reqGR.requested_for = gr.sys_id;
                    ritm.requested_for = gr.sys_id;

            } else if (email.from == "ifguestuser@email.com") {
                // gs.info('Mustafa@SN' + requestedForEmail);
                ritm.requested_for = SnUser;
            }
            ritm.update();

        }


    }





})(current, event, email, logger, classifier);
3 REPLIES 3

Ankur Bawiskar
Tera Patron

@Mustafa4 

try this

(function runAction(current, event, email, logger, classifier) {

    var senderEmail = (email.from || '').toString().trim();
    var SnUser = gs.getProperty("ag.sys_user.xml_integration_user.sys_id");

    var rawBody = '';
    if (email.body_text)
        rawBody = email.body_text.toString();
    else if (email.body_html)
        rawBody = email.body_html.toString();
    else {
        gs.error('SuccessFactors Email: Email body is empty');
        return;
    }

    rawBody = rawBody.replace(/\r/g, '').trim();

    // Find XML start
    var xmlStart = rawBody.indexOf('<?xml');
    if (xmlStart === -1) {
        gs.error('SuccessFactors Email: No XML found in email body');
        return;
    }

    // Extract only the XML payload, not the whole tail of the email
    var xmlEndTag = '</SuccessFactorsRequest>';
    var xmlEnd = rawBody.indexOf(xmlEndTag, xmlStart);
    if (xmlEnd === -1) {
        gs.error('SuccessFactors Email: Closing XML tag not found');
        return;
    }

    var xmlPayload = rawBody.substring(xmlStart, xmlEnd + xmlEndTag.length).trim();

    // Optional cleanup for malformed text produced by some email clients
    xmlPayload = xmlPayload.replace(/<mailto:[^>]*>/gi, '');
    xmlPayload = xmlPayload.replace(/\[mailto:[^\]]*\]/gi, '');
    xmlPayload = xmlPayload.replace(/&nbsp;/gi, ' ');

    var j;
    try {
        j = gs.xmlToJSON(xmlPayload);
    } catch (ex) {
        gs.error('SuccessFactors Email: XML parsing exception - ' + ex.message);
        return;
    }

    if (!j || !j.SuccessFactorsRequest) {
        gs.error('SuccessFactors Email: XML parsing failed or missing root element');
        return;
    }

    var reqObj = j.SuccessFactorsRequest;

    var summary = reqObj.Summary ? reqObj.Summary.toString().trim() : '';
    var description = reqObj.DetailDescription ? reqObj.DetailDescription.toString().trim() : '';
    var requestedForEmail = reqObj.RequestedFor ? reqObj.RequestedFor.toString().trim() : '';
    var priorityText = reqObj.RequestPriority ? reqObj.RequestPriority.toString().trim() : '';

    if (!summary) {
        gs.error('SuccessFactors Email: Summary is empty');
        return;
    }

    var requestedForSysId = '';
    if (requestedForEmail) {
        var userGR = new GlideRecord("sys_user");
        userGR.addQuery('email', requestedForEmail);
        userGR.setLimit(1);
        userGR.query();
        if (userGR.next())
            requestedForSysId = userGR.getUniqueValue();
    }

    try {
        var cart = new Cart();
        var item = cart.addItem('906a49bc1b0ee110e533759d1e4bcbc1');

        cart.setVariable(item, 'summary', summary);
        cart.setVariable(item, 'detail_description', description);
        cart.setVariable(item, 'requested_by', SnUser);
        cart.setVariable(item, 'request_priority', priorityText);

        var requestRecord = cart.placeOrder();
        if (!requestRecord || !requestRecord.number) {
            gs.error('SuccessFactors Email: Request was not created from cart');
            return;
        }

        var reqNumber = requestRecord.number.toString();

        var reqGR = new GlideRecord('sc_request');
        reqGR.addQuery('number', reqNumber);
        reqGR.setLimit(1);
        reqGR.query();
        if (reqGR.next()) {
            reqGR.opened_by = SnUser;

            if (requestedForSysId)
                reqGR.requested_for = requestedForSysId;
            else if (senderEmail == "ifguestuser@email.com")
                reqGR.requested_for = SnUser;

            reqGR.update();
        }

        var ritm = new GlideRecord('sc_req_item');
        ritm.addQuery('request.number', reqNumber);
        ritm.query();
        while (ritm.next()) {
            ritm.opened_by = SnUser;

            if (requestedForSysId)
                ritm.requested_for = requestedForSysId;
            else if (senderEmail == "ifguestuser@email.com")
                ritm.requested_for = SnUser;

            ritm.update();
        }

    } catch (e) {
        gs.error('SuccessFactors Email: Request creation failed - ' + e.message);
    }

})(current, event, email, logger, classifier);

💡 If my response helped, please mark it as correct and close the thread 🔒— this helps future readers find the solution faster! 🙏

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

Hi Ankur,

I really appreciate your quick response. I have updated the script based on your suggestion and tested it; however, the issue still persists.

Specifically, when the email body contains hyperlinks or images, the request is not being created. I have attached the email logs for your reference. I also tried making a few modifications on my end, but I am still unable to resolve the issue.

Could you please review the error logs below? If you’re able to identify a solution, it would be extremely helpful.

Email Log :-

Skipping script 'Update Incident (BP)', email is type 'new', which does not match Inbound Email Action's type 'reply'

Skipping script 'Unsubscribe from Notification', condition 'subjectSTARTSWITHUnsubscribe from^EQ' failed

Skipping script 'Create Live Feed Reply', email is type 'new', which does not match Inbound Email Action's type 'reply'

Stop processing detected after executing script: Create SuccessFactors Request (XML)

Skipping script 'Create Live Feed Like Reply', email is type 'new', which does not match Inbound Email Action's type 'reply'

Skipping script 'Update Request Item', email is type 'new', which does not match Inbound Email Action's type 'reply'

Create SuccessFactors Request (XML) : did not create or update sc_req_item using current

Skipping script 'Process CAB meeting invite replies', condition 'subjectSTARTSWITHTentative: CAB Meeting: Your attendance is requested in CAB^ORsubjectSTARTSWITHAccepted: CAB Meeting: Your attendance is requested in CAB^ORsubjectSTARTSWITHDeclined: CAB Meeting: Your attendance is requested in CAB^EQ' failed

Skipping script 'Process task activity', email is type 'new', which does not match Inbound Email Action's type 'reply'

Skipping script 'Create Epic', condition 'email.subject.indexOf("Epic:") == 0' failed

Skipping script 'Create Incident(RA)', condition 'subjectSTARTSWITHException Request^EQ' failed

Skipping script 'Create Feedback via Forwarded Email', email is type 'new', which does not match Inbound Email Action's type 'forward'

Skipping script 'Create Feedback via New Email', condition 'new FeedbackEmailUtils().mailReceivedToFeedbackCreationEmailId(email.to)' failed

Skipping script 'Create Story', condition 'email.subject.indexOf("Story:") == 0' failed

Skipping script 'Create Enhancement', condition 'email.subject.indexOf("Enhancement:") == 0' failed

Email is classified as new for triggers execution

Skipping script 'Create Defect', condition 'email.subject.indexOf("Defect:") == 0 || email.subject.indexOf("Bug:")' failed

Trigger 3c3696c5931db6d091ffbccdfaba1081 email conditions not satisfied, skipping

Received id=<PH7PR12MB6394C47586F8846D156CB8829C082@PH7PR12MB6394.namprd12.prod.outlook.com> Classified as new

Ready for update




Hi Ankur,

Have you found any solution to my issue? It would be greatly helpful to me.