Email Script - How to check if attachment has attached file

Lisa Goldman
Kilo Sage

Hello,

 

I have the following two attachment variables in the Catalog Item.  

 

LisaGoldman_0-1710198483578.png

How to write an if else statement in email script to check if the attachment variable has attached file or not?

if attachment is there, displays "file is attached" else "please attach a file"

 

Thank you

 

 

 
1 ACCEPTED SOLUTION

Hi @Lisa Goldman ,

 

try with below code

 

(function runMailScript( /* GlideRecord */ current, /* TemplatePrinter */ template,
     /* Optional EmailOutbound */
     email, /* Optional GlideRecord */ email_action,
     /* Optional GlideRecord */
     event) {
     var image1 = current.variables.attach_image1;
     var image2 = current.variables.attach_image2;

     if (image1 != '' && image2 != '') { // when both the variables have attachment attached
         var gr = new GlideRecord('sys_attachment');
         gr.addQuery('table_sys_id', current.sysapproval);
         gr.addQuery('content_type', "CONTAINS", "image");
         gr.query();
         while (gr.next()) {
             template.print('<img src=/sys_attachment.do?sys_id=' + gr.getValue("sys_id") + ' width="400" height="300">');
             template.print("<br>");
             template.print("<br>");
         }
     } else if(image1 != '' || image2 != '') { // when only 1 of the variable has attachment attached
var gr = new GlideRecord('sys_attachment');
         gr.addQuery('table_sys_id', current.sysapproval);
         gr.addQuery('content_type', "CONTAINS", "image");
         gr.query();
         if (gr.next()) {
             template.print('<img src=/sys_attachment.do?sys_id=' + gr.getValue("sys_id") + ' width="400" height="300">');
             template.print("<br>");
             template.print("<br>");
         }
}else{
         return false;
     }
 })(current, template, email, email_action, event);
 

 

Thanks,

Danish

View solution in original post

14 REPLIES 14

Danish Bhairag2
Tera Sage
Tera Sage

Hi @Lisa Goldman ,

 

Where do u want to do this validation? Like while submitting the form or later

 

Thanks,

Danish

Hello @Danish Bhairag2 

It supposed to print on the email body.  I think I got it to works:

 

 

LisaGoldman_1-1710204875470.png

Thank you

 

@Danish Bhairag2 

I don't think my code is correct.  I would like to validation when an end user attached the file on the portal.  Thanks 

Amit Verma
Kilo Patron
Kilo Patron

Hi @Lisa Goldman 

 

Any particular reason for doing this validation in email script ? You can check for the attachments with an On-Submit Catalog Client Script as well to ensure the attachments are available. Please refer :

https://www.servicenow.com/community/itsm-articles/attachment-variable-making-attachment-mandatory-i...

 

Thanks and Regards

Amit Verma


Please mark this response as correct and helpful if it assisted you with your question.