logo

NJP

Adding attachments to Email

Import · Sep 25, 2020 · article

Hi,

In this article, i will show you how we can add attachments to email. The recommended way is to use Include Attachments checkbox in the notification.

Once you check the Include attachments, the attachments associated with that record will be sent as attachment over the mail. This is pretty straight forward.

What if you want to send some other attachment through email which is not attached to this record but has to go along with this notification?

Option 1 (if that attachment is static like some disclaimer document that you want to send along with the notification of all records)

1. Upload the attachment in sys_attachment table through some record

2. Copy the attachment sys_id

3. Create a Before Insert Business Rule on sys_email table

Add conditions

Subject contains

Script

(function executeRule(current, previous /*null when async*/ ) {
    // Add your code here
            var grSysAtt = new GlideRecord('sys_attachment');
            grSysAtt.get('ab1fc95cdbaf101082f21780399619ff'); //mention your attachment sys_id
            var content = new GlideSysAttachment().getContentStream(grSysAtt.sys_id);
            new GlideSysAttachment().writeContentStream(current, grSysAtt.getValue('file_name'), grSysAtt.getValue('content_type'), content);
})(current, previous);

Save

This will send that specific document as attachment in the email.

Option2: what if you want to send a dynamic attachment but not directly linked to this record

For Example, Fetch the parent incident documents along with the child incident documents and send it as attachment.

Business Rule on sys_email

Before insert

Conditions

Target table is incident

subject contains ...

Select Include Attachments checkbox in the notification (This will attach all the emails of your child incident)

Script to fetch parent incident attachments

(function executeRule(current, previous /*null when async*/ ) {
    // fetch the parent incident
    var gr = new GlideRecord("incident");
    if (gr.get(current.instance)) {
    var parent = gr.parent;
        var grSysAtt = new GlideRecord('sys_attachment');
        grSysAtt.addQuery("table_sys_id", gr.parent);
        grSysAtt.query();
        while (grSysAtt.next()) {
            var content = new GlideSysAttachment().getContentStream(grSysAtt.sys_id);
            new GlideSysAttachment().writeContentStream(current, grSysAtt.getValue('file_name'), grSysAtt.getValue('content_type'), content);
        }
    }
})(current, previous);

Let me know if you have any questions in the comments below.

Mark the article as helpful and bookmark if you found it useful.

Regards,Asif

2020 ServiceNow Community MVP

View original source

https://www.servicenow.com/community/developer-articles/adding-attachments-to-email/ta-p/2320991