office 365 management api example for sending email , fetch emails and delete in laravel
Use the access token to delete emails using the Microsoft Graph API using laravel Http::withToken - (search query for Chatgpt)
- Set up the Microsoft Graph API and get the access token.
use Illuminate\Support\Facades\Http;
$graphUrl = 'https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token';
$response = Http::asForm()->post($graphUrl, [
'client_id' => env('O365_CLIENT_ID'),
'scope' => 'https://graph.microsoft.com/.default',
'client_secret' => env('O365_CLIENT_SECRET'),
'grant_type' => 'client_credentials',
]);
$accessToken = $response['access_token'];
- Use the access token to send an email using the Microsoft Graph API.
use Illuminate\Support\Facades\Http;
$graphUrl = 'https://graph.microsoft.com/v1.0/users/{userPrincipalName}/sendMail';
$response = Http::withToken($accessToken)->post($graphUrl, [
'message' => [
'subject' => 'Test email',
'body' => [
'contentType' => 'Text',
'content' => 'This is a test email.'
],
'toRecipients' => [
[
'emailAddress' => [
'address' => 'example@example.com'
]
]
]
],
'saveToSentItems' => 'true'
]);
if ($response->ok()) {
// Email sent successfully
} else {
// Email sending failed
}
Use the access token to fetch emails using the Microsoft Graph API.
use Illuminate\Support\Facades\Http; $accessToken = 'your_access_token_here'; $response = Http::withToken($accessToken) ->get('https://graph.microsoft.com/v1.0/me/messages'); if ($response->ok()) { // Handle successful response $emails = $response->json()['value']; } else { // Handle error response $error = $response->json()['error']['message']; }
Get latest emails
To fetch the latest emails using the Microsoft Graph API with Laravel's Http::withToken, you can add the
$top
parameter to the API endpoint to limit the number of emails returned in the response. Here's an example of how to fetch the latest 10 emails using the Microsoft Graph API with Laravel:use Illuminate\Support\Facades\Http; $accessToken = "YOUR_ACCESS_TOKEN"; $response = Http::withToken($accessToken) ->get('https://graph.microsoft.com/v1.0/me/messages?$top=10&$orderby=receivedDateTime desc'); if ($response->successful()) { $emails = $response->json(); // Process the emails } else { // Handle the error }
Delete message
To delete emails using the Microsoft Graph API with Laravel's Http::withToken, you can use the HTTP
DELETE
method to make a request to the/messages/{id}
endpoint of the API. Here's an example of how to delete an email using the Microsoft Graph API with Laravel:
use Illuminate\Support\Facades\Http;
$accessToken = "YOUR_ACCESS_TOKEN";
$emailId = "EMAIL_ID_TO_BE_DELETED";
$response = Http::withToken($accessToken)
->delete("https://graph.microsoft.com/v1.0/me/messages/$emailId");
if ($response->successful()) {
// Email deleted successfully
} else {
// Handle the error
}