'Read MS-Exchange emails from a custom folder using EWS managed api Nodejs implementation

Is there a way to read emails from a custom folder in MS-Exchange using EWS managed api (NodeJs implementation)? I'm able to read from the Inbox, but I have custom folder names where the emails are moved to that I'd like to have the code read in those folders.

what I have tried.

const EWS = require('node-ews');
const ewsConfig = {
    username: '<Email>',
    password: '<Password>',
    host: '<Exchange URL>'
};
const ews = new EWS(ewsConfig);
const ewsFunction = 'FindItem';
var ewsArgs = {
    'attributes': {
        'Traversal': 'Shallow'
    },
    'ItemShape': {
        't:BaseShape': 'IdOnly',
        't:AdditionalProperties': {
            't:FieldURI': {
                'attributes': {
                    'FieldURI': 'item:Subject'
                }
            }
        }
    },
    'ParentFolderIds': {
        'DistinguishedFolderId': {
            'attributes': {
                'Id': '<Some Custom Folder>'
            }
        }
    }
};

(async function () {
   
    try {
        let result = await ews.run(ewsFunction, ewsArgs);
        console.log(result);
    } catch (err) {
        console.log(err.message);
    }
})();
    

ERROR:

a:ErrorInvalidRequest: The request is invalid.: {"ResponseCode":"ErrorInvalidRequest","Message":"The request is invalid."}


Solution 1:[1]

DistinguishedFolderId won't work for non default folders so I would suggest you try

    'ParentFolderIds': {
        'FolderId': {
            'attributes': {
                'Id': '<Some Custom Folder>'
            }
        }
    }

Solution 2:[2]

The way I got this to work was to first find the FolderId using the FindFolder call:

const ewsArgs = {
  FolderShape: {
    BaseShape: 'AllProperties',
  },
  ParentFolderIds: {
    DistinguishedFolderId: {
      attributes: {
        Id: 'inbox',
      },
      Mailbox: {
        EmailAddress: '[email protected]',
      },
    },
  },
};

const { ResponseMessages } = await ews.run('FindFolder', ewsArgs, ews.ewsSoapHeader);

const found = ResponseMessages.FindFolderResponseMessage.RootFolder.Folders.Folder
  .find(f => f.DisplayName.match(new RegExp(folderName.toLowerCase(), 'ig')));

After that you can use it to find all of the emails in the folder with the FindItem call:

const ewsArgs = {
  attributes: {
    Traversal: 'Shallow',
  },
  ItemShape: {
    BaseShape: 'IdOnly',
    // BaseShape: 'AllProperties',
  },
  ParentFolderIds: {
    FolderId: found.FolderId,
  },
};

const { ResponseMessages } = await ews.run('FindItem', ewsArgs, ews.ewsSoapHeader);

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 Glen Scales
Solution 2 Michael Cox