To read and send emails using Office 365 with PHP, you'll typically use the Microsoft Graph API. Here’s a step-by-step guide to get you started:
Prerequisites
- Office 365 Account: Ensure you have an Office 365 account.
- Azure App Registration: Register an application in Azure AD to get the Client ID, Tenant ID, and Client Secret.
- PHP Environment: Ensure you have a PHP environment set up.
Steps
1. Register an Application in Azure AD
- Go to the Azure Portal.
- Navigate to "Azure Active Directory" > "App registrations" > "New registration".
- Fill in the required details and register the app.
- Note the Application (client) ID and Directory (tenant) ID.
- Create a Client Secret in "Certificates & secrets" and note it.
2. Set Required API Permissions
- In the registered app, navigate to "API permissions" > "Add a permission".
- Select "Microsoft Graph".
- Add delegated permissions for
Mail.Read
,Mail.ReadWrite
,Mail.Send
.
3. Install Microsoft Graph PHP SDK
Install the Microsoft Graph SDK for PHP via Composer:
composer require microsoft/microsoft-graph
4. Authenticate and Get Access Token
Use the OAuth2 authentication flow to get an access token. Here’s an example using the league/oauth2-client
package:
composer require league/oauth2-client
Here’s a PHP script to authenticate and get the access token:
<?php
require 'vendor/autoload.php';
use League\OAuth2\Client\Provider\GenericProvider;
$provider = 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' => '',
'scopes' => 'https://graph.microsoft.com/.default'
]);
// Get the authorization URL
$authorizationUrl = $provider->getAuthorizationUrl();
// Get the state generated for you to store it for later
$state = $provider->getState();
// Redirect to authorization URL
header('Location: ' . $authorizationUrl);
// Get access token
if (isset($_GET['code'])) {
try {
// Try to get an access token using the authorization code grant.
$accessToken = $provider->getAccessToken('authorization_code', [
'code' => $_GET['code']
]);
echo 'Access Token: ' . $accessToken->getToken();
} catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
exit($e->getMessage());
}
}
?>
5. Use Microsoft Graph SDK to Read and Send Emails
Here's an example script to read and send emails:
<?php
require 'vendor/autoload.php';
use Microsoft\Graph\Graph;
use Microsoft\Graph\Model;
$accessToken = 'YOUR_ACCESS_TOKEN';
$graph = new Graph();
$graph->setAccessToken($accessToken);
// Reading emails
$messages = $graph->createRequest("GET", "/me/mailFolders/inbox/messages")
->setReturnType(Model\Message::class)
->execute();
foreach ($messages as $message) {
echo $message->getSubject() . "\n";
}
// Sending an email
$sendMailBody = [
"message" => [
"subject" => "Meet for lunch?",
"body" => [
"contentType" => "Text",
"content" => "The new cafeteria is open."
],
"toRecipients" => [
[
"emailAddress" => [
"address" => "example@example.com"
]
]
]
]
];
$graph->createRequest("POST", "/me/sendMail")
->attachBody($sendMailBody)
->execute();
echo "Mail sent!";
?>
Summary
- Register an application in Azure AD to get the Client ID, Tenant ID, and Client Secret.
- Set the necessary API permissions for Microsoft Graph.
- Authenticate using OAuth2 and obtain an access token.
- Use Microsoft Graph SDK to interact with Office 365 emails.
Ensure you replace placeholders like YOUR_CLIENT_ID
, YOUR_CLIENT_SECRET
, YOUR_TENANT_ID
, and YOUR_ACCESS_TOKEN
with your actual credentials and tokens.