How to get all mails of Outlook using Ms Graph API in Laravel
How To Read Emails Using Microsoft Graph API In Laravel
In this post, you will be learning how to get all mails of Outlook using MS Graph API in Laravel.
Before we dive into the code, you need to ensure you have the following prerequisites:
- Laravel Project Setup
- Access Token of MS Graph API (How to get Access Token of Ms Graph API)
We will be working with get all mails, Search mail, pagination (paginate the mails), sort by date functionality. So now let's get started:
Step 1: Create a controller named MsGraphController.php and paste the below code
class MicrosoftGraphController extends Controller
{
public function getAllMails(Request $request)
{
$paginateNo = $request->has('top') ? $request->top : 50;
$skipToken = $request->has('skipToken') ? $request->skipToken : '';
$skip = $request->has('skip') ? $request->skip : 0;
$searchEmailQuery = $request->has('search') ? $request->search : '';
$user = Auth::user();
if(!$user->msGraphToken){
return response()->json([
'message' => 'Access token not found'
], 401);
}
$accessToken = $user->msGraphToken->access_token; //Provide the access_token
/**
* Note: The query parameter '$skip' is not supported with '$search'.
*/
if($searchEmailQuery){
$response = Http::withHeaders([
'Authorization' => 'Bearer ' . $accessToken,
'Accept' => 'application/json',
])->get('https://graph.microsoft.com/v1.0/me/messages', [
'$select' => 'sender,from,toRecipients,ccRecipients,bccRecipients,subject,body,isRead,isDraft,createdDateTime,receivedDateTime,hasAttachments',
'$search' => '"'.$searchEmailQuery.'"',
'$top' => $paginateNo,
'$skipToken' => $skipToken,
]);
}else{
$response = Http::withHeaders([
'Authorization' => 'Bearer ' . $accessToken,
'Accept' => 'application/json',
])->get('https://graph.microsoft.com/v1.0/me/messages', [
'$select' => 'sender,from,toRecipients,ccRecipients,bccRecipients,subject,body,isRead,isDraft,createdDateTime,receivedDateTime,hasAttachments',
'$top' => $paginateNo,
'$skip' => $skip,
'$filter' => 'isDraft eq false',
]);
}
if ($response->successful()) {
// $emails = $response->json();
$messages = $response->json()['value'];
$nextLink = $response->json()['@odata.nextLink'] ?? null;
// Check if sorting is requested
if ($request->has('sortBy') && $request->sortBy === 'date')
{
$receivedDateTimes = array_column($messages, 'receivedDateTime');
array_multisort($receivedDateTimes, $request->sortDir == 'desc' ? SORT_DESC:SORT_ASC, $messages);
}
elseif ($request->has('sortBy') && $request->sortBy === 'status')
{
$receivedIsReadStatus = array_column($messages, 'isRead');
array_multisort($receivedIsReadStatus, $request->sortDir == 'desc' ? SORT_DESC:SORT_ASC, $messages);
}
return response()->json([
'message' => 'Email list successful',
'data' => $messages,
'nextLink' => $nextLink,
]);
} else {
// Handle error response
$errorMessage = $response->json('error');
return response()->json([
'message' => 'Failed to fetch message',
'data' => $errorMessage,
], $response->status());
}
}
}
Step 2: Create an API in following path: routes/api.php
use App\Http\Controllers\MsGraphController;
Route::prefix('v1/ms-graph')->group( function () {
Route::post('/emails', [MsGraphController::class, 'getAllMails']);
});
Step 3: Input fields allowed to get mail for above code. You can also see these request fields in controller.
- input name: top | Validation: Not Mandatory, Integer input.
- input name: skipToken | Validation: Not Mandatory.
- input name: skip | Validation: Not Mandatory, integer input.
- input name: search | Validation: Not Mandatory, string input.
That's it. Now you can list all the mails with search, paginate and sort by date functionality.