Garethp / php-ews

PHP Exchange Web Services
BSD 3-Clause "New" or "Revised" License
112 stars 45 forks source link

Trouble in getting search results from combined restriction #228

Open AndreasSchmitt opened 2 years ago

AndreasSchmitt commented 2 years ago

I'm trying to get all mails from a folder that are a.) unread b.) newer than a special date. Each single restriction works fine in this call:

$mailItems = $api->getMailItems( $subFolder->getFolderId(), $options);

The AND combined restriction does not - not sure what is going wrong.

First the working restrictions:

$options = array(
    'Restriction' => array(
            'IsGreaterThanOrEqualTo' => array(
              'dateTimeReceived' => $fromDate
            )
    )
);

$options = array(
    'Restriction' => array(
        'IsEqualTo' => array(
            'IsRead' => false
        )
    )
);

The combined that does not work:

$options = array(
    'Restriction' => array(
        'And' => array( 
            'IsGreaterThanOrEqualTo' => array( 'dateTimeReceived' => $fromDate ),
            'IsEqualTo' => array( 'IsRead' => false )
        )
    )
);

would be very happy for any hint.

l0ckm4 commented 2 years ago

I'm late to the party but this works for me. Also uses impersonation, pagination of results as well as trawling sub folder rather than root Inbox.

$host     = 'myexch';
$username = 'myuser';
$password = 'mypassword';

$api = MailAPI::withUsernameAndPassword($host, $username, $password, ['impersonation' => 'someone@somewhere.com','timezone' => 'GMT Standard Time']);
$folder = $api->getFolderByDisplayName('MyFolder', \garethp\ews\API\Enumeration\DistinguishedFolderIdNameType::INBOX);
$folderId = $folder->getfolderId();

$datefilter = date("F d 07:00:00", strtotime('today'));
$date = new DateTime($datefilter);

$restriction = [
    'And' => [
        'IsGreaterThan' => ['DateTimeReceived' => $date->format('c')],
        'And' => [
            'IsEqualTo' => [
                'IsRead' => false
            ]
        ]
    ]
];  

$emails = array();
$i=0;
$step = 50;

do {
    $results = $api->getMailItems($folderId, [
        'IndexedPageItemView' => [
            'MaxEntriesReturned' => $step,
            'Offset' => $i,
            'BasePoint' => 'Beginning'
        ],
        'Restriction' => $restriction
    ]);
    foreach ($results as $z=>$a) {
        $emails[] = $a->getSubject();
    }
    $i = $i+$step;
} while ($results->isIncludesLastItemInRange()===false);

print_r($emails);