PHP:如何使用msgraph-sdk-php从Outlook获取电子邮件列表?

huangapple go评论65阅读模式
英文:

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

问题

  1. You can access the values of the object properties, such as bodyPreview, when iterating through $outlook_emails by using the arrow (->) notation to access object properties in PHP. Here's how you can do it:
foreach ($outlook_emails as $email) {
     print($email->getBodyPreview());
}
  1. To get the messages for an email thread, you typically need to use the /conversations/{id}/messages endpoint in the Microsoft Graph API, where {id} is the ID of the email conversation or thread you want to retrieve messages for. Here's an example of how you can use it:
$conversationId = 'AAQkA6vM6AD4'; // Replace with the actual conversation ID

$messages = $graph->createRequest("GET", "/conversations/{$conversationId}/messages")
    ->setReturnType(Model\Message::class)
    ->execute();

This will retrieve the messages associated with the specified conversation ID. Make sure to replace 'AAQkA6vM6AD4' with the actual conversation ID you want to query.

英文:

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": "<CAsZwAyQ@mail.gmail.com>",
    "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 <developer@xxxxxxx.onmicrosoft.com> 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> <\/div><br><div class=\"gmail_quote\"><div dir=\"ltr\" class=\"gmail_attr\">On Wed, Jun 21, 2023 at 4:56\u202fPM FNU LNU <<a href=\"mailto:developer@08fxt.onmicrosoft.com\">developer@08fxt.onmicrosoft.com<\/a>> 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": "zzzzz@zzzzzz.com"
        }
    },
    "from": {
        "emailAddress": {
            "name": "xxxx",
            "address": "xxxxx"
        }
    },
    "toRecipients": [{
        "emailAddress": {
            "name": "FNU LNU",
            "address": "developer@xxxxt.onmicrosoft.com"
        }
    }],
    "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?

答案1

得分: 1

如果您想获取一组消息,请改用 createCollectionRequest 而不是 createRequest。将返回类型更改为 Model\Message

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

相同线程的消息具有相同的 conversationId。如果您知道 conversationId,您可以过滤消息:

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

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();

huangapple
  • 本文由 发表于 2023年6月22日 11:09:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76528370.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定