Install Required Packages
- Make sure you have Composer installed to manage PHP dependencies. Use it to require the Microsoft Graph SDK for PHP by running:
composer require microsoft/microsoft-graph
Configure Authentication
- Create an authentication provider using Microsoft Identity platform libraries. You'll need an OAuth 2.0 based setup to get an access token. The token will be used in API calls to authenticate requests.
- For simplicity, use the `League\OAuth2\Client\Provider\GenericProvider` class. It helps in setting up necessary OAuth 2.0 credentials like `clientId`, `clientSecret`, `urlAuthorize`, `urlAccessToken`, and `urlResourceOwnerDetails`.
use League\OAuth2\Client\Provider\GenericProvider;
$oauthClient = new GenericProvider([
'clientId' => 'YOUR_CLIENT_ID',
'clientSecret' => 'YOUR_CLIENT_SECRET',
'redirectUri' => 'YOUR_REDIRECT_URI',
'urlAuthorize' => 'https://login.microsoftonline.com/YOUR_TENANT_ID/oauth2/v2.0/authorize',
'urlAccessToken' => 'https://login.microsoftonline.com/YOUR_TENANT_ID/oauth2/v2.0/token',
'urlResourceOwnerDetails' => '',
]);
$accessToken = $oauthClient->getAccessToken('authorization_code', [
'code' => 'YOUR_AUTH_CODE'
]);
Initialize Microsoft Graph Client
- Import and instantiate the GraphServiceClient using the SDK, passing the access token in a delegate to provide token acquisition logic to the client.
use Microsoft\Graph\Graph;
$graph = new Graph();
$graph->setAccessToken($accessToken->getToken());
Fetch Email Data
- Once authenticated, use the graph client to fetch email data. For example, to get the messages for the signed-in user from their primary mailbox:
$messages = $graph->createRequest('GET', '/me/messages')
->setReturnType(Microsoft\Graph\Model\Message::class)
->execute();
- Optionally, filter or sort emails by providing query parameters, like ordering by received date:
$messages = $graph->createRequest('GET', '/me/messages?$orderby=receivedDateTime DESC')
->setReturnType(Microsoft\Graph\Model\Message::class)
->execute();
Process and Display Emails
- Iterate over the message collection and extract required properties from each message object.
- Print the email details to the console, store in a database, or process as needed for your application.
foreach ($messages as $message) {
echo 'Subject: ' . $message->getSubject() . "\n";
echo 'From: ' . $message->getFrom()->getEmailAddress()->getAddress() . "\n";
echo 'Received: ' . $message->getReceivedDateTime() . "\n";
echo "--------------------------------------------\n";
}
These steps outline how you can fetch email data using the Microsoft Graph API in PHP. Ensure you have the right permissions configured for your application in Azure to access mail data.