Search code examples
phpoutlookmicrosoft-graph-apioffice365microsoft-graph-mail

PHP: How do I get a list of emails from Outlook using msgraph-sdk-php?


I'm trying to retrieve Outlook emails and using this library https://github.com/microsoftgraph/msgraph-sdk-php

This is my code:

$tenantId     = 'aaaaaaaaaaaaaaa';
$clientId     = 'bbbbbbbbbbbbbbb';
$clientSecret = 'ccccccccccccccc';

$inbox_id = 'dddddddddddddd';

$guzzle      = new \GuzzleHttp\Client();
$url         = 'https://login.microsoftonline.com/' . $tenantId . '/oauth2/v2.0/token';
$token       = json_decode($guzzle->post($url, [
    'form_params' => [
        'client_id'     => $clientId,
        'client_secret' => $clientSecret,
        'scope'         => 'https://graph.microsoft.com/.default',
        'grant_type'    => 'client_credentials',
    ],
])->getBody()->getContents());
$accessToken = $token->access_token;


$graph = new Graph();
$graph->setAccessToken($accessToken);

$outlook_emails = $graph->createRequest("GET",
    "/users/xxxxxxxxxxxxxx/mailFolders/" . $inbox_id . "/messages")
    ->setReturnType(Model\User::class)
    ->execute();

This is a sample response:

$outlook_emails>>>
[{
    "@odata.etag": "W\/\"CQAAABYAAACR8bcfZf8uSKGEvkK2\"",
    "id": "AAMkAGQOAAAAAAEMAACR8bcfZf8uSKGh7OAAAEvmH6AAA=",
    "createdDateTime": "2023-06-21T21:57:23Z",
    "lastModifiedDateTime": "2023-06-21T21:57:23Z",
    "changeKey": "CQAAABYAAAAEvkK2",
    "categories": [],
    "receivedDateTime": "2023-06-21T21:57:23Z",
    "sentDateTime": "2023-06-21T21:56:42Z",
    "hasAttachments": false,
    "internetMessageId": "<[email protected]>",
    "subject": "Re: this is a second thread",
    "bodyPreview": "this is a second thread b\r\n\r\n\r\nOn Wed, Jun 21, 2023 at 4:56\u202fPM FNU LNU <[email protected]> wrote:\r\nthis is a second thread",
    "importance": "normal",
    "parentFolderId": "AAMkhTgfAlP7OAAAAAAEMAAA=",
    "conversationId": "AAQkA6vM6AD4=",
    "conversationIndex": "AQHZpUKIgvPq8zoAPq+VzXAA",
    "isDeliveryReceiptRequested": null,
    "isReadReceiptRequested": false,
    "isRead": false,
    "isDraft": false,
    "webLink": "https:\/\/outlook.office365.com\/owa\/?ItemID=AAMAAA%3D&exvsurl=1&viewmodel=ReadMessageItem",
    "inferenceClassification": "focused",
    "body": {
        "contentType": "html",
        "content": "<html><head>\r\n<meta http-equiv=\"Content-Type\" content=\"text\/html; charset=utf-8\"><\/head><body><div dir=\"ltr\"><span style=\"color:rgb(0,0,0); font-family:Calibri,Arial,Helvetica,sans-serif; font-size:16px\">this is a second thread b<\/span><div class=\"gmail-yj6qo\" style=\"color:rgb(0,0,0); font-family:Calibri,Arial,Helvetica,sans-serif; font-size:16px\"><\/div>&nbsp;<\/div><br><div class=\"gmail_quote\"><div dir=\"ltr\" class=\"gmail_attr\">On Wed, Jun 21, 2023 at 4:56\u202fPM FNU LNU &lt;<a href=\"mailto:[email protected]\">[email protected]<\/a>&gt; wrote:<br><\/div><blockquote class=\"gmail_quote\" style=\"margin:0px 0px 0px 0.8ex; border-left:1px solid rgb(204,204,204); padding-left:1ex\"><div class=\"msg-6004113959439972472\"><div dir=\"ltr\"><div style=\"font-family:Calibri,Arial,Helvetica,sans-serif; font-size:12pt; color:rgb(0,0,0)\">this is a second thread<br><\/div><\/div><\/div><\/blockquote><\/div><\/body><\/html>"
    },
    "sender": {
        "emailAddress": {
            "name": "zzzzz",
            "address": "[email protected]"
        }
    },
    "from": {
        "emailAddress": {
            "name": "xxxx",
            "address": "xxxxx"
        }
    },
    "toRecipients": [{
        "emailAddress": {
            "name": "FNU LNU",
            "address": "[email protected]"
        }
    }],
    "ccRecipients": [],
    "bccRecipients": [],
    "replyTo": [],
    "flag": {
        "flagStatus": "notFlagged"
    }
}
...
]

When I try to iterate through $outlook_emails I get this error "message": "Cannot use object of type Microsoft\\Graph\\Model\\User as array",

foreach ($outlook_emails as $email) {
     print($email['bodyPreview']);
}
  1. How can I get the values of the object, for example, bodyPreview when iterating through $outlook_emails?
  2. What API endpoint do I need to use to get the messages for an email thread?

Solution

  • If you want to get a collection of messages, use createCollectionRequest instead of createRequest. Change return type to Model\Message

    $outlook_emails = $graph->createCollectionRequest("GET",
        "/users/xxxxxxxxxxxxxx/mailFolders/" . $inbox_id . "/messages")
        ->setReturnType(Model\Message::class)
        ->execute();
    

    Messages from the same thread have the same conversationId. If you know the conversationId you can filter messages

    $conversationId = "xxx"
    $outlook_emails = $graph->createCollectionRequest("GET",
        "/users/xxxxxxxxxxxxxx/mailFolders/" . $inbox_id . "/messages?$filter=conversationId eq " . $conversationId)
        ->setReturnType(Model\Message::class)
        ->execute();