Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
Redmond desk10 min

How to Send Email From PHP Through Microsoft 365 on a LAMP Server

A practical guide to sending PHP mail through Microsoft 365 from a LAMP server: install PHPMailer, configure STARTTLS on port 587, use Entra OAuth2, grant Send As correctly, and choose between client submission, relay, and Direct Send.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use PHPMailer as the SMTP client in your PHP application, connect to smtp.office365.com on port 587 with STARTTLS, and authenticate with Microsoft Entra OAuth2 (the modern, preferred method). The web server needs outbound TCP 587, OpenSSL with TLS 1.2 or 1.3, and a licensed Microsoft 365 mailbox with SMTP AUTH allowed. Keep the authenticated mailbox as the From address unless it has explicit Send As permission.

This setup is called client SMTP submission. It is different from SMTP relay and Direct Send, which use your tenant’s MX endpoint on port 25 and have different authentication and recipient rules.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What you need before writing PHP code

Confirm these conditions on the LAMP host and in the Microsoft 365 tenant first. Most apparent PHP SMTP failures are policy, network, or mailbox problems rather than PHPMailer bugs.

  • A PHP application running on Linux with Composer available.
  • PHPMailer installed from its maintained Composer package.
  • A licensed Microsoft 365 or Office 365 mailbox for client SMTP submission.
  • DNS resolution for smtp.office365.com.
  • Outbound TCP port 587 allowed by the server firewall, cloud provider, and any hosting control panel. Port 25 is also documented, but 587 is the recommended submission port.
  • PHP OpenSSL support capable of negotiating TLS 1.2 or TLS 1.3.
  • SMTP AUTH enabled for the mailbox and not blocked by an organization policy or Security Defaults.
  • An Entra application and OAuth credentials if you use the preferred Modern Authentication flow.

Microsoft says client submission must use the DNS name smtp.office365.com, not an IP address, and must negotiate STARTTLS. Do not replace the hostname with a resolved address.

Why PHP’s built-in mail() is not the Office 365 solution

PHP’s mail() function usually hands a message to a local mail server, commonly through a sendmail binary on Linux, BSD, and macOS. It does not, by itself, provide the Microsoft 365 hostname, STARTTLS negotiation, OAuth2, or SMTP policy handling required here.

A PHP SMTP library gives your application explicit control over the remote connection, authentication, envelope, headers, and diagnostics. PHPMailer is a practical choice because it supports SMTP, Composer installation, and XOAUTH2 authentication.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Install PHPMailer with Composer

From the directory containing your PHP application’s composer.json, run:

composer require phpmailer/phpmailer

Load Composer’s autoloader in the script that sends mail:

require __DIR__ . '/vendor/autoload.php';

Keep the vendor directory and your lock file deployed with the application, or run Composer during deployment. Do not copy credentials into the package source or commit them to version control.

Normal Microsoft 365 SMTP settings

These are the standard client-submission values for a PHP web application:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Setting Value Why it matters
SMTP host smtp.office365.com Microsoft’s client-submission DNS name; use the name, not an IP address.
Port 587 Recommended submission port; outbound access must be unblocked.
Encryption STARTTLS The connection begins in plain SMTP and is upgraded to TLS before authentication.
TLS versions TLS 1.2 or TLS 1.3 Required server capability according to Microsoft’s setup guidance.
Authentication SMTP AUTH with OAuth2/XOAUTH2 Modern Authentication is preferred over password-only Basic authentication.
Mailbox Licensed Microsoft 365 mailbox Required for client SMTP submission.
From address Normally the authenticated mailbox A different sender requires Send As permission.

Build a basic PHPMailer SMTP sender

The following example shows the transport configuration and a complete message. It assumes that the application obtains its mailbox address and secret values from environment variables or a secret manager rather than from source code.

<?php

use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;

require __DIR__ . '/vendor/autoload.php';

$mail = new PHPMailer(true);

try {
    $mail->isSMTP();
    $mail->Host       = 'smtp.office365.com';
    $mail->Port       = 587;
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->SMTPAuth   = true;

    // Use the OAuth2 block in the next section for current tenants.
    $mail->Username = getenv('M365_SMTP_USERNAME');
    $mail->Password = getenv('M365_SMTP_PASSWORD');

    $mail->setFrom(getenv('M365_SMTP_USERNAME'), 'Website');
    $mail->addAddress('[email protected]');
    $mail->Subject = 'Test message from PHP';
    $mail->Body    = 'This message was sent through Microsoft 365 SMTP.';
    $mail->AltBody = 'This message was sent through Microsoft 365 SMTP.';

    $mail->send();
    echo 'Message sent';
} catch (Exception $e) {
    error_log('Mail send failed: ' . $mail->ErrorInfo);
    http_response_code(500);
    echo 'Message could not be sent';
}

Password authentication is shown only to make the SMTP properties clear. Microsoft recommends Modern Authentication, and Basic authentication can be incompatible with Security Defaults. Use the OAuth2 configuration below for a new deployment.

Use Microsoft Entra OAuth2 (XOAUTH2)

OAuth2 avoids putting a mailbox password in the SMTP client. The flow has three parts:

  1. Register an application in Microsoft Entra.
  2. Obtain an access token using the application’s approved credentials and a refresh token or another supported OAuth flow.
  3. Present that token to the SMTP server using PHPMailer’s XOAUTH2 mechanism.

Request the SMTP permission scope https://outlook.office.com/SMTP.Send. Consent and token issuance are controlled by your tenant’s Entra policies, so the person administering the tenant may need to grant consent or approve the application.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

PHPMailer OAuth2 transport pattern

PHPMailer’s official Azure example uses this SMTP pattern:

$mail->isSMTP();
$mail->Host       = 'smtp.office365.com';
$mail->Port       = 587;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->SMTPAuth   = true;
$mail->AuthType   = 'XOAUTH2';
$mail->setOAuth($oauthProvider);

$oauthProvider must be an OAuth provider configured with the Entra client ID, client secret (when the selected flow requires one), refresh token, and the username of the mailbox. PHPMailer passes the resulting access token through XOAUTH2 during SMTP authentication. Keep the provider object and all token material outside the public web root and out of logs.

Set the From address correctly

Set the sender to the same mailbox represented by the OAuth identity unless that identity has Send As permission on another mailbox:

$mail->setFrom($oauthUsername, 'Website');

Outlook generally expects the From address to match the logged-in user. If the application authenticates as [email protected] but sends as [email protected], an administrator must grant the service account Send As permission for the billing mailbox. Without it, Microsoft documents the non-delivery report (NDR) text: 5.7.60 SMTP; Client doesn't have permissions to send as this sender.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Enable SMTP AUTH and check tenant policy

SMTP AUTH can be disabled at the organization or mailbox level. Microsoft states that organizations created after January 2020 have SMTP AUTH disabled by default, and it can be enabled for the designated mailbox. Security Defaults and other authentication policies can also block Basic authentication.

For a mailbox submission deployment, the administrator should verify all of the following in the Microsoft 365 administration and Exchange settings:

  • The mailbox has an appropriate Microsoft 365 or Office 365 license.
  • Authenticated SMTP is enabled for that mailbox.
  • No tenant-wide policy, conditional access rule, or Security Defaults setting blocks the selected authentication method.
  • The Entra application has the required SMTP.Send permission and tenant consent where required.
  • Send As permission exists for any sender address different from the authenticating mailbox.

Do not respond to a login failure by blindly enabling legacy password authentication. First determine whether the tenant requires OAuth2 and whether the mailbox is permitted to use SMTP AUTH.

Protect secrets and tokens on a LAMP server

OAuth2 improves authentication, but a stolen refresh token can still allow mail access. Apply ordinary server-side secret hygiene:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Store client secrets, refresh tokens, and mailbox identifiers in environment variables, a secrets manager, or a file readable only by the web-process account.
  • Keep secret files outside the document root so a web-server misconfiguration cannot serve them.
  • Do not commit .env files, token caches, or diagnostic output to Git.
  • Rotate client secrets and revoke refresh tokens according to your organization’s policy.
  • Use a dedicated mailbox with only the permissions required by the application.
  • Never print the access token, refresh token, client secret, or full SMTP transcript in a user-facing error.

Test the server before blaming PHP

Run these checks from the same LAMP host that executes PHP:

  1. Resolve the hostname with the server’s normal DNS resolver. A failed lookup means the application cannot reach Microsoft regardless of its PHP settings.
  2. Verify that outbound TCP 587 is allowed by the host firewall and hosting provider. A connection timeout usually indicates filtering rather than bad credentials.
  3. Confirm that the PHP build has OpenSSL enabled. Without it, PHPMailer cannot negotiate STARTTLS.
  4. Check that the operating system and PHP/OpenSSL combination supports TLS 1.2 or TLS 1.3.
  5. Send a message to an address you control and inspect both the application log and the recipient’s mailbox.

Do not substitute an IP address after a DNS test. Microsoft requires the smtp.office365.com DNS name, and certificate validation depends on using the correct hostname.

Choose the right Microsoft 365 delivery method

Client SMTP submission is usually the right starting point for a PHP site because it supports authenticated sending to internal and external recipients and saves sent messages to Sent Items. It is not the only option.

Method Connection Authentication and prerequisites Recipient behavior and use case
Client SMTP submission smtp.office365.com, port 587 or 25, TLS Licensed mailbox, mailbox authentication, SMTP AUTH enabled Internal and external recipients; normal choice for a PHP web app. Microsoft’s current published limits are 10,000 recipients per day and 30 messages per minute.
SMTP relay Tenant MX endpoint, port 25, TLS Inbound connector plus a static, unshared public IP or a certificate; a licensed mailbox is not required Useful for a controlled server or when mailbox-submission limits are insufficient. Connector administration is required.
Direct Send Tenant MX endpoint, port 25 No licensed mailbox, but it is restricted by Microsoft 365 recipient rules Microsoft 365 recipients only; unsuitable for Internet-facing transactional mail. SPF, DKIM, and DMARC still matter for domain protection.
High Volume Email Microsoft-managed high-volume service Availability and quotas depend on the tenant and region Intended for internal-recipient workloads where ordinary submission is not appropriate.
Azure Communication Services Email Separate Microsoft email service Availability, pricing, and quotas depend on the tenant and region Option for internal and external recipients when client submission is not suitable.

The 10,000-recipient daily and 30-message-per-minute figures are Microsoft’s 2026 current guidance for client SMTP submission, not a promise that every tenant or mailbox will behave identically under every anti-abuse policy. A recipient is counted according to Microsoft’s service rules, so design your queue and retry behavior conservatively.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

When to use relay or Direct Send instead

SMTP relay for a controlled server

Relay is appropriate when a known server can identify itself through an inbound connector using a static, unshared public IP or certificate. It avoids requiring a licensed sending mailbox, but it moves responsibility to connector administration, IP reputation, TLS configuration, and strict source control. A shared hosting IP generally does not satisfy the static-IP requirement.

Direct Send for Microsoft 365-only recipients

Direct Send also uses the tenant MX endpoint on port 25 and does not require a licensed mailbox. It is restricted to Microsoft 365 recipients, so it cannot be the general solution for password resets, invoices, or notifications sent to arbitrary Internet addresses. If a site needs external delivery, use client submission or an approved external-capable service.

High-volume workloads

If a site routinely approaches the client-submission limits, do not create many mailboxes to evade them. Evaluate connector-based relay, Microsoft’s High Volume Email option for internal mail, or Azure Communication Services Email for internal and external recipients. Availability, pricing, and quotas vary by tenant and region and must be checked for the intended deployment.

Diagnose common failures

“Connection timed out” or “Could not connect to SMTP host”

  • Test DNS resolution for smtp.office365.com.
  • Check outbound TCP 587 in the Linux firewall, cloud security group, and hosting provider policy.
  • Confirm the script is not trying to connect to port 25 when the provider blocks it.
  • Check that the server clock is accurate; large clock errors can break TLS and token validation.

“Could not authenticate” or repeated OAuth failures

  • Confirm $mail->AuthType = 'XOAUTH2' is set when using a token.
  • Verify that the token was issued for the SMTP.Send scope https://outlook.office.com/SMTP.Send.
  • Check that the Entra application has tenant consent and that the refresh token has not expired or been revoked.
  • Verify SMTP AUTH is enabled for the mailbox and is not blocked by Security Defaults or another tenant policy.
  • Ensure the OAuth username identifies the same mailbox you intend to use as the sender.

TLS or certificate negotiation errors

  • Confirm PHP has the OpenSSL extension and that the server supports TLS 1.2 or TLS 1.3.
  • Use smtp.office365.com, not an IP address or an unrelated relay hostname.
  • Check that the server’s CA certificate bundle is current enough to validate Microsoft’s certificate chain.
  • Do not disable certificate verification as a “fix”; correct the hostname, CA bundle, or system clock instead.

“Client doesn’t have permissions to send as this sender”

The authenticated mailbox and From address do not match, and Send As permission is missing. Either set setFrom() to the authenticated mailbox or have an administrator grant Send As permission on the alternate mailbox. The documented NDR is 5.7.60 SMTP; Client doesn't have permissions to send as this sender.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Messages send but do not arrive

  • Check the PHPMailer result and server response, then inspect the recipient’s junk, quarantine, and mail-flow logs.
  • Verify the envelope and From domain are authorized by your organization’s SPF, DKIM, and DMARC design.
  • Confirm the application is not exceeding the 30-messages-per-minute or 10,000-recipients-per-day client-submission guidance.
  • Queue transient failures and retry with backoff rather than repeatedly opening parallel SMTP sessions.

Use PHPMailer debugging safely

During a controlled diagnosis, PHPMailer can emit an SMTP transcript. Enable it only temporarily, direct it to a protected server log, and disable it before production traffic:

$mail->SMTPDebug = 2;

Never expose the transcript in an HTTP response. Redact usernames where practical and remove passwords, access tokens, refresh tokens, and client secrets from logs. A successful test should end with debugging disabled:

$mail->SMTPDebug = 0;

Production design checklist

  • Use Composer-managed PHPMailer and deploy the matching lock file.
  • Use smtp.office365.com, port 587, and STARTTLS.
  • Prefer Entra OAuth2/XOAUTH2 with the https://outlook.office.com/SMTP.Send scope.
  • Store secrets and tokens outside source control and the document root.
  • Use a licensed mailbox with SMTP AUTH enabled for client submission.
  • Set From to the authenticated mailbox unless Send As is granted.
  • Check DNS, outbound TCP 587, OpenSSL, and TLS support from the actual LAMP host.
  • Log failures without credentials or tokens, and turn off SMTP debugging after diagnosis.
  • Queue mail and rate-limit sends so the application remains below Microsoft’s current client-submission guidance.
  • Move to relay or an approved high-volume service when mailbox submission is not technically or operationally appropriate.

What the finished configuration accomplishes

With PHPMailer connected to smtp.office365.com:587 over STARTTLS, an approved OAuth2 token, and a mailbox permitted to use SMTP AUTH, PHP can submit authenticated messages through Microsoft 365 to internal and external recipients. The security boundary is shared: PHPMailer controls the SMTP conversation, while Microsoft Entra, Exchange policies, mailbox permissions, DNS, TLS, and network egress determine whether that conversation is allowed.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.