'How to search and get a specific file using Google Apps Script to search in the Parent folder and in its subfolders?

The issue I'm current facing is:

I created a main folder named "Parent" with the folder ID:eg abcde12345.

Within the Parent folder, there are 3 diff folders (eg. Folder A, Folder B, Folder C) with their own files.

The specific file I am looking for is: "File to be sent.pdf"

This file, I placed in Folder C for example.

However, the script I wrote below (with some details edited out) only search for the specific file in the Parent folder. The search does not go into Folder A,B or C to look for the file with the exact filename.

Is there a way to search for this specific file within the Parent + A + B + C without hardcode the Folder A,B,C IDs in the script?

Thank you!

Ps. The number of sub folders may grow more than A,B,C and in these sub folders, I am thinking of creating more layers.

function ReturnWork(){
 
var markedFolder = DriveApp.getFolderById("abcde12345");
 
var ws = SpreadsheetApp.getActiveSpreadsheet();
 
/*This section which I edited out to shorten this post contains variables example:
-emailAddress
-subject
-etc... all details needed for the mailApp below.*/
 
 
var docName = 'File to be sent.pdf';
var markedFiles = markedFolder.getFilesByName(docName);


      if(markedFiles.hasNext()){
      MailApp.sendEmail({
      to: emailAddress,
      subject: subjectMarked,
      replyTo: centre_email,
      htmlBody : markedHTML.evaluate().getContent(),
      attachments: [markedFiles.next().getAs(MimeType.PDF)],
      });
    }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source