To send emails from your Azure-hosted PHP application using Microsoft 365, follow these simple steps using Microsoft Graph API:
1. Register Your Application in Azure
- Go to Azure Portal: Visit Azure Portal.
- Create an App Registration:
- Navigate to Azure Active Directory > App registrations.
- Click New registration and follow the prompts to create an application.
- Save the Application (client) ID and Directory (tenant) ID that you get.
2. Set Up API Permissions
- Add Permissions:
- In your app registration, go to API permissions > Add a permission.
- Choose Microsoft Graph > Delegated permissions.
- Add
Mail.Send
to allow sending emails.
3. Generate a Client Secret
- Create a Secret:
- Go to Certificates & secrets > New client secret.
- Describe the secret and set an expiration time.
- Click Add and save the secret value. This is your password.
4. Get an Access Token
- Request an Access Token:
- Make a POST request to the token URL:
POST https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token
- Use these parameters in your request:
grant_type=client_credentials client_id={client_id} client_secret={client_secret} scope=https://graph.microsoft.com/.default
- The response will include an access token you’ll use for authentication.
- Make a POST request to the token URL:
5. Send an Email
- Use Microsoft Graph API:
- Make a POST request to:
POST https://graph.microsoft.com/v1.0/me/sendMail
- Include the access token in the
Authorization
header:Authorization: Bearer {access_token}
- Send the email content in JSON format:
{ "message": { "subject": "Test Email", "body": { "contentType": "Text", "content": "This is a test email." }, "toRecipients": [ { "emailAddress": { "address": "recipient@example.com" } } ] } }
- Make a POST request to: