To send an email using PHP with Microsoft OAuth 2.0 authentication, you will need to:
- Register your application with Microsoft and get the necessary credentials (client ID and client secret). You can do this by following the steps outlined in the Microsoft documentation: https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app
- Install the PHP OAuth 2.0 client library. You can use Composer to install the PHP OAuth 2.0 client library:
composer require league/oauth2-client
Use the OAuth 2.0 client library to get an access token. You can use the following code to get an access token:
use LeagueOAuth2ClientProviderMicrosoft;
$provider = new Microsoft([
'clientId' => 'your-client-id',
'clientSecret' => 'your-client-secret',
'redirectUri' => 'http://your-redirect-uri/'
]);
// If the user has not authorized your app, redirect them to the Microsoft login page
if (!isset($_GET['code'])) {
$authUrl = $provider->getAuthorizationUrl();
header('Location: '.$authUrl);
exit;
// If the user has authorized your app, get an access token
} else {
$accessToken = $provider->getAccessToken('authorization_code', [
'code' => $_GET['code']
]);
}
Use the access token to send an email using the Microsoft Graph API. You can use the following code to send an email using the Microsoft Graph API
use GuzzleHttpClient;
$client = new Client();
$response = $client->post('https://graph.microsoft.com/v1.0/me/sendMail', [
'headers' => [
'Authorization' => 'Bearer '.$accessToken,
'Content-Type' => 'application/json'
],
'json' => [
'message' => [
'subject' => 'Email subject',
'body' => [
'contentType' => 'Text',
'content' => 'Email body'
],
'toRecipients' => [
[
'emailAddress' => [
'address' => 'recipient@example.com'
]
]
]
],
'saveToSentItems' => 'true'
]
]);