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);
1 REPLY 1

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