Search code examples
phpphp-ews

Getting Single Mail via garethp/php-ews


Code:

$api = MailAPI::withUsernameAndPassword($server, $username, $password);
$folder1 = $api->getFolderByDisplayName('PubFolder', DistinguishedFolderIdNameType::PUBLICFOLDERSROOT);
$subFolder1 = $api->getFolderByDisplayName($data['mailfolder'], $folder1->getFolderId());
$api->setFolderId($subFolder1->getFolderId());

$mail = $api->getMailItems($data['id']);

Error: Exception 'Error' with message 'Call to a member function toXmlObject() on string'

Description: I'd like to get a single Mail item via the id, however since i need to call it from a different page and load the content via JS i am unable to send the MailID object which i can get by using $singleMail->getItemId() inside a foreach. So i have to use $singleMail->getItemId()->getId() which yields the ID as a string, however when trying to get the mail via ID I get the above error.

So, how should i proceed? Requesting all Mails and looping till i find the ID again is not an option.

Am I using getMailItems() wrongly? If so please correct me.

Can i Create the correct ID-Object somehow?

Or is there an alternative way to query a Single Mail via the ID-String? Optionally I would be looking for the manuel building of the Query.


Solution

  • getMailItems does not take an email id, but a folder id and it requires it to be an object ($folderId) for the first parameter and you're giving a string. If you go and check the MailAPI::getMailItems source, you will understand exactly why you get that error. At line 91 we see:

    'FolderId' => $folderId->toXmlObject()
    

    there your code tries to call a member function from a string. I searched a bit and I think you can filter the mails by id with getMailItems by using the optional parameter $options.

    First, try to set the ItemId to have the string value of mail id like this:

    $mail = $api->getMailItems($subFolder1->getFolderId(), [
        'ItemIds' => [
            'ItemId' => $data['id'] // Or (new API\Type\ItemIdType($data['id']))
        ]
    ]);
    

    If that won't work, then try to search again for the mail by using this code:

    $mail = $api->getItem(new API\Type\ItemIdType($data['id']));
    

    I don't have an EWS to test this, but I think that's the way you're going to solve the problem.