How to map the email body to addtional comments in activity section

mania
Tera Contributor

Hi,

I have a forward inbound action, in that i have two block of codes are working like below:

A)Forwarded Email with Existing Case Number in Subject:
1.System locates the case.
2.Maps time worked from the email to the case.
3.Copies the email body into the work notes.
4.Copies any attachments from the email and links them in the work notes.
B)Forward Email Matching the existing Case Number in Subject:
1.System creates a new case record.
2.Maps time worked from the email to the case.
3.Copies the email body into the additional comments.
4.Copies any attachments from the email and links them in the additional comments.
Here A block is working fine and the body is mapped to the worknotes properly in activity section as below screensort:
mania_0-1756712540622.png

 

but in B block of code the case is created but the body with any inline image is not mapped properly to the additional comments in activity.
The body is getting mapped in Customer Visible Work notes as below:
mania_1-1756712653773.png

 But in addtional comment the inline image is not getting mapped as below:

mania_3-1756712777910.png

 

Note:I have two fields Work notes internal and Customer Visible Work notes so both are html type
so if i add any text or image in to the Work notes internal that value goes automatically in to the worknotes in activity section
same as Customer Visible Work notes if i add any text or image in to the Customer Visible Work notes that value goes automatically in to the Addtional comments in activity section.
Here is my forward inbound script:

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

    var caseSysId = handleEmail();

    function handleEmail() {

        var subject = email.subject || '';

        var caseNumber = extractCaseNumber(subject);

        gs.info("Checking Case Number from email subject: " + caseNumber);

        if (caseNumber) {

            var existingCase = new GlideRecord('sn_customerservice_case');

            existingCase.addQuery('number', caseNumber);

            existingCase.query();

            if (existingCase.next()) {

                gs.info("Existing case found: " + caseNumber);

                // Update time worked example

                var timeWorkedRaw = existingCase.getValue('time_worked');

                var gdt = new GlideDateTime(timeWorkedRaw);

                var totalSeconds = gdt.getNumericValue() / 1000 + 1;

                var gd = new GlideDuration(totalSeconds * 1000);

                existingCase.setValue('time_worked', gd.getDurationValue());

                existingCase.u_add_worknotes = email.body_html; // ✅ keep inline HTML/images

                existingCase.update();

                copyAttachmentsFromEmailToCase(email.sys_id, existingCase.sys_id); // ✅ pass both IDs

                return existingCase.sys_id;

            }

        }

        // ---------- No case found → Create new ----------

        var newCase = new GlideRecord("sn_customerservice_case");

        newCase.initialize();

        newCase.short_description = subject || "Forwarded Email";

        newCase.state = 1;

        newCase.assignment_group = '30540397ff2f1e10f7f3fe4bfc4fd9ff';

        newCase.contact_type = "email";

        // Map sender to contact BEFORE insert

        var senderemail = getSenderEmail();

        if (senderemail) {

            var contactGr = new GlideRecord('customer_contact');

            contactGr.addQuery('email', senderemail);

            contactGr.query();

            if (contactGr.next()) {

                newCase.contact = contactGr.sys_id;

                newCase.u_task_account = contactGr.account || '7de3fc51fffb1650f7f3fe4bfc4fd94c';

                newCase.u_task_site = contactGr.u_site || '8e04b091fffb1650f7f3fe4bfc4fd99c';

            }

        }

        var insertedId = newCase.insert();

        gs.info("Created new case with sys_id: " + insertedId);

 

        // Update comments after insert

        var createdCase = new GlideRecord("sn_customerservice_case");

        if (createdCase.get(insertedId)) {

            var cleanText = email.body_text; // ServiceNow automatically provides plain text version

            var forwardedBodyText = "Forwarded by: " + (email.origemail || '') + "\n\n" + cleanText;

            createdCase.u_customer_visible_comments = "Forwarded by: " + (email.origemail || '') + "<br><br>" +       email.body_html; // full HTML

            createdCase.comments = forwardedBodyText; // plain text only

            createdCase.update();

        }

        // Copy attachments

        copyAttachmentsFromEmailToCase(email.sys_id, insertedId); // ✅ fixed params

        return insertedId;

    }

    function extractCaseNumber(subject) {

        var regex = /(?:^|[^a-zA-Z0-9])((CS)\d{7})(?!\w)/i;

        var match = subject.match(regex);

        return match ? match[1].toUpperCase() : null;

    }

    function getSenderEmail() {

        if (email.body && email.body.from) {

            var fm = email.body.from || '';

            var match = fm.match(/<([^>]+)>/);

            return match ? match[1].trim() : fm.trim();

        }

        return '';

    }

    function copyAttachmentsFromEmailToCase(emailSysId, caseSysId) {

        var gsa = new GlideSysAttachment();

        var emailAttachmentGR = new GlideRecord('sys_attachment');

        emailAttachmentGR.addQuery('table_name', 'sys_email');

        emailAttachmentGR.addQuery('table_sys_id', emailSysId);

        emailAttachmentGR.query();

        while (emailAttachmentGR.next()) {

            var fileName = emailAttachmentGR.getValue('file_name');

            var sizeBytes = emailAttachmentGR.getValue('size_bytes');

            var sourceSysId = emailAttachmentGR.getValue('sys_id');

            var contentType = emailAttachmentGR.getValue('content_type');

            var caseAttachmentGR = new GlideRecord('sys_attachment');

            caseAttachmentGR.addQuery('table_name', 'sn_customerservice_case');

            caseAttachmentGR.addQuery('table_sys_id', caseSysId);

            caseAttachmentGR.addQuery('file_name', fileName);

            caseAttachmentGR.addQuery('size_bytes', sizeBytes);

            caseAttachmentGR.query();

            if (!caseAttachmentGR.hasNext()) {

                var caseGR = new GlideRecord('sn_customerservice_case');

                if (caseGR.get(caseSysId)) {

                    var stream = gsa.getContentStream(sourceSysId);

                    gsa.writeContentStream(caseGR, fileName, contentType, stream);

                    gs.info('Copied attachment: ' + fileName);

                }

            } else {

                gs.info('Skipped duplicate attachment: ' + fileName);

            }

        }

    }

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

Can anyone please help on this where i missed on code, it will be helpful.

Thanks!

 
3 REPLIES 3

Collin Romeijn
Mega Guru

Hi Mania,

could it be that Additional comments OOTB is not in HTML format?
Maybe this article provides some intel on this:
Solved: Re: How to paste inline images in comments and wor... - ServiceNow Community

Kind regards,

Collin

@Collin Romeijn 

Additional comments OOTB is not in HTML format? - No

We have a another custome field as html type so if we enter any values in that html field it will update automatically on addtional comments on activity

Thanks!

kaushal_snow
Mega Sage

Hi @mania ,

 


Go to System Policy > Email > Inbound Actions.

Create a new inbound action or modify an existing one that targets the appropriate table (e.g., sn_customerservice_case).

 

Add below script:

(function runAction(current, event, email, logger, classifier) {
// Check if the email body is in HTML format
if (email.body_html) {
// Map the email body to the Additional Comments field
current.u_additional_comments = email.body_html;
current.update();
} else {
// Handle plain text email body if necessary
gs.info("Email body is not in HTML format.");
}
})(current, event, email, logger, classifier);


This script checks if the email body is in HTML format and then maps it to the u_additional_comments field of the current record. Ensure that the field name (u_additional_comments) matches the actual field name in your table....

 

If you found my response helpful, please mark it as ‘Accept as Solution’ and ‘Helpful’. This helps other community members find the right answer more easily and supports the community...

 

 

Thanks and Regards,
Kaushal Kumar Jha - ServiceNow Consultant - Lets connect on Linkedin: https://www.linkedin.com/in/kaushalkrjha/