Site icon Mailtrap

How to send emails using PHPMailer and Office 365 SMTP

This image is a comical graphic representation of PHPMailer and Office 365 for an article that covers the topic in detail.

Since you’re reading this, I’m pretty sure you went to the official Microsoft docs and realized the PHPMailer Office 365 setup isn’t as easy as you thought. 

No worries, we worked out the complexities and I’ll hold your hand every step of the way. In this article, I cover the following:

PHPMailer setup and configuration

I’ll cover the PHPMailer setup and configuration from scratch. Also, there’s a separate section dedicated to OAuth2 to authenticate the SMTP connection. 

Step 1: Installing PHPMailer

I’m using the standard command to install PHPMailer via Composer. It pulls the latest version of PHPMailer (at the time of writing it was 6.9.1). 

composer require phpmailer/phpmailer

Step 2: PHPMailer configuration for Office 365

Here’s the basic setup for Office 365. Note that this is just for shows and the stepped approach. Soon, I’ll update the code with OAuth2, which is critical if you want to send via the outgoing SMTP server. 

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);

try {
    //Server settings
    $mail->isSMTP();
    $mail->Host       = 'smtp.office365.com';
    $mail->SMTPAuth   = true;
    $mail->SMTPSecure = 'tls';
    $mail->Port       = 587;

    //OAuth2 authentication setup goes here (covered below)
   
    //Sender and recipient settings
    $mail->setFrom('youremail@yourdomain.com', 'Your Name');
    $mail->addAddress('recipient@domain.com', 'Recipient Name');

    //Content
    $mail->isHTML(true);
    $mail->Subject = 'Test Email';
    $mail->Body    = 'This is a test email using Office 365 SMTP and PHPMailer.';
   
    //Send email
    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

Step 3: OAuth authentication

Microsoft is deprecating basic authentication for security reasons. The OAuth2 is now the recommended method for authenticating with Office 365. 

It takes quite a few steps and is more complicated compared to the basic flow, so I’ll break it down for you into more manageable chunks.

Step 3.1: Use Azure AD to register an application

  1. Log into the Azure portal and go to Azure Active Directory (Microsoft Entra ID)
  2. Under App registrations, click New Registration.
  3. Give your app a name (e.g., “PHPMailer OAuth2”).
  4. Leave “Supported account types” by default
  5. Set the Redirect URI type to “Public client/native” and provide a redirect URI (e.g., http://localhost).
  6. Register the app.
  7. Get the Client ID and Tenant ID on the “Overview” page
  8. Under API permissions, add permissions for “APIs my organization uses” and find Office 365 Exchange Online
    1. Choose “Application permissions,” select “SMTP.SendAsApp” and click “Add permissions”
    2. After press the button “Grant admin consent for {your_user_name}” and confirm
  9. Optional. Create a new Client Secret on the “Certificates & secrets” page (provide a description and expiry date)

Important: Save the Client ID, Tenant ID, and Client Secret (optional) for later use. 

Step 3.2: Enable OAuth2 with PHPMailer

First, install the necessary package using the command below.

composer require greew/oauth2-azure-provider

Next, I’ll update the PHPMailer configuration to reflect the changes. 

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\OAuth;
//@see https://github.com/greew/oauth2-azure-provider
use Greew\OAuth2\Client\Provider\Azure;

require 'vendor/autoload.php';

$email = getenv('AZURE_OFFICE365_EMAIL'); // your office365 email
$clientId = getenv('AZURE_CLIENT_ID'); // Azure Client ID
$tenantId = getenv('AZURE_TENANT_ID'); // Azure Tenant ID
$clientSecret = getenv('AZURE_CLIENT_SECRET_VALUE'); // Optional. Azure Client Secret Value (Certificates & secrets)
$refreshToken = getenv('AZURE_REFRESH_TOKEN');

$mail = new PHPMailer(true);

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

   // Set OAuth2 token
   $mail->AuthType = 'XOAUTH2';
   $mail->setOAuth(new OAuth([
       'provider' => new Azure([
           'clientId' => $clientId,
           'tenantId' => $tenantId,
           'clientSecret' => $clientSecret
       ]),
       'clientId' => $clientId,
       'refreshToken' => $refreshToken,
       'clientSecret' => $clientSecret,
       'userName' => $email,
   ]));

   //Sender and recipient settings
   $mail->setFrom($email, 'First Last'); // your office365 email
   $mail->addAddress('someone@someserver.com', 'John Doe');

   //Content
   $mail->isHTML(true);
   $mail->Subject = 'OAuth2 Email Test';
   $mail->Body    = 'This is a test email using OAuth2 authentication with Office 365 SMTP and PHPMailer.';

   //Send email
   $mail->send();
   echo 'Message has been sent';
} catch (Exception $e) {
   echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

Quick breakdown:

Important: The code above contains placeholders AZURE_CLIENT_ID, AZURE_CLIENT_SECRET_VALUE, AZURE_TENANT_ID, etc. Make sure to replace these with your actual variables. 

Get an OAuth2 token from the provider

To send emails, you first need an OAuth token. The PHPMailer library already has a default file for this purpose, which you can run on your local server to get the required ‘refreshToken.’ 

Hit the link for reference, and here’s a quick setup tutorial. 

Setup:

If you don’t want to use the built-in form, set your Client ID, tenant ID, secret, and provider inside the file and run it using the console.

As a result, if everything is entered correctly, you should see a message like this: “Refresh Token: …YOUR_REFRESH_TOKEN…..” Save this refresh token somewhere; we will need it in the future.

Quick breakdown:

Send email using Office 365 SMTP

To send emails using Office 365, you need to configure PHPMailer with Office 365’s SMTP settings. Below I included the SMTP server details and a simple example to send a plain-text email.

Of course, I’m assuming that you’re done with OAuth2 and Azure AD. Otherwise, the described methodology won’t work. 

SMTP server details:

Here’s the script to send a plain text message. 

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\OAuth;
//@see https://github.com/greew/oauth2-azure-provider
use Greew\OAuth2\Client\Provider\Azure;

require 'vendor/autoload.php';

$email = getenv('AZURE_OFFICE365_EMAIL'); // your office365 email
$clientId = getenv('AZURE_CLIENT_ID'); // Azure Client ID
$tenantId = getenv('AZURE_TENANT_ID'); // Azure Tenant ID
$clientSecret = getenv('AZURE_CLIENT_SECRET_VALUE'); // Optional. Azure Client Secret Value (Certificates & secrets)
$refreshToken = getenv('AZURE_REFRESH_TOKEN');

$mail = new PHPMailer(true);

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

   // Set OAuth2 token
   $mail->AuthType = 'XOAUTH2';
   $mail->setOAuth(new OAuth([
       'provider' => new Azure([
           'clientId' => $clientId,
           'tenantId' => $tenantId,
           'clientSecret' => $clientSecret
       ]),
       'clientId' => $clientId,
       'refreshToken' => $refreshToken,
       'clientSecret' => $clientSecret,
       'userName' => $email,
   ]));

   //Sender and recipient settings
   $mail->setFrom($email, 'First Last'); // your office365 email
   $mail->addAddress('someone@someserver.com', 'Recipient Name');


//    $mail->addAddress('someone@someserver.com', 'John Doe');

   //Content
   $mail->isHTML(true);
   $mail->Subject = 'OAuth2 Email Test';
   $mail->Body    = 'This is a test email using OAuth2 authentication with Office 365 SMTP and PHPMailer.';

   //Send email
   $mail->send();
   echo 'Message has been sent';
} catch (Exception $e) {
   echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

Quick breakdown:

Send email to multiple recipients

Here’s an example of how to send an email to multiple recipients. I’ll include CC and BCC recipients to showcase how it’s done.

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\OAuth;
//@see https://github.com/greew/oauth2-azure-provider
use Greew\OAuth2\Client\Provider\Azure;

require 'vendor/autoload.php';

$email = getenv('AZURE_OFFICE365_EMAIL'); // your office365 email
$clientId = getenv('AZURE_CLIENT_ID'); // Azure Client ID
$tenantId = getenv('AZURE_TENANT_ID'); // Azure Tenant ID
$clientSecret = getenv('AZURE_CLIENT_SECRET_VALUE'); // Optional. Azure Client Secret Value (Certificates & secrets)
$refreshToken = getenv('AZURE_REFRESH_TOKEN');

$mail = new PHPMailer(true);

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

   // Set OAuth2 token
   $mail->AuthType = 'XOAUTH2';
   $mail->setOAuth(new OAuth([
       'provider' => new Azure([
           'clientId' => $clientId,
           'tenantId' => $tenantId,
           'clientSecret' => $clientSecret
       ]),
       'clientId' => $clientId,
       'refreshToken' => $refreshToken,
       'clientSecret' => $clientSecret,
       'userName' => $email,
   ]));

   //Sender and recipient settings
   $mail->setFrom($email, 'First Last'); // your office365 email

   $mail->addAddress('recipient1@domain.com', 'Recipient One'); // Main recipient
   $mail->addCC('recipient2@domain.com', 'Recipient Two'); // CC recipient
   $mail->addBCC('recipient3@domain.com', 'Recipient Three'); // BCC recipient

   //Content
   $mail->isHTML(false);  // Send plain-text email
   $mail->Subject = 'Test Email with Multiple Recipients';
   $mail->Body    = 'This is a test email sent to multiple recipients using OAuth2 authentication with Office 365 SMTP and PHPMailer.';

   //Send email
   $mail->send();
   echo 'Message has been sent';
} catch (Exception $e) {
   echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

Quick breakdown:

You can add as many recipients as needed using the addAddress() method for the main recipient, addCC() for Carbon Copy (CC), and addBCC() for Blind Carbon Copy (BCC). 

Even so, note that there are specific Office throughput limits. Anyway, the logic of adding multiple recipients in the example is as follows:

Send email with attachments

Check the snippet to send emails with attachments. 

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\OAuth;
//@see https://github.com/greew/oauth2-azure-provider
use Greew\OAuth2\Client\Provider\Azure;

require 'vendor/autoload.php';

$email = getenv('AZURE_OFFICE365_EMAIL'); // your office365 email
$clientId = getenv('AZURE_CLIENT_ID'); // Azure Client ID
$tenantId = getenv('AZURE_TENANT_ID'); // Azure Tenant ID
$clientSecret = getenv('AZURE_CLIENT_SECRET_VALUE'); // Optional. Azure Client Secret Value (Certificates & secrets)
$refreshToken = getenv('AZURE_REFRESH_TOKEN');

$mail = new PHPMailer(true);

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

   // Set OAuth2 token
   $mail->AuthType = 'XOAUTH2';
   $mail->setOAuth(new OAuth([
       'provider' => new Azure([
           'clientId' => $clientId,
           'tenantId' => $tenantId,
           'clientSecret' => $clientSecret
       ]),
       'clientId' => $clientId,
       'refreshToken' => $refreshToken,
       'clientSecret' => $clientSecret,
       'userName' => $email,
   ]));

   // Sender and recipient settings
   $mail->setFrom($email, 'Your Name'); // your office365 email
   $mail->addAddress('recipient@domain.com', 'Recipient Name');

   // Add an attachment
   $mail->addAttachment('/path/to/office365_attachment.jpg', 'office365_attachment.jpg');  // Replace with your file path and name

   // Email content
   $mail->isHTML(false);  // Send plain-text email
   $mail->Subject = 'Test Email with Attachment';
   $mail->Body    = 'This is a test email with an attachment sent using OAuth2 authentication with Office 365 SMTP and PHPMailer.';

   //Send email
   $mail->send();
   echo 'Message has been sent';
} catch (Exception $e) {
   echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

Quick breakdown:

I’ll focus only on the attachments section since I already covered other functions. 

Common errors:

Send HTML email

Here’s how to send an HTML email. 

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\OAuth;
//@see https://github.com/greew/oauth2-azure-provider
use Greew\OAuth2\Client\Provider\Azure;

require 'vendor/autoload.php';

$email = getenv('AZURE_OFFICE365_EMAIL'); // your office365 email
$clientId = getenv('AZURE_CLIENT_ID'); // Azure Client ID
$tenantId = getenv('AZURE_TENANT_ID'); // Azure Tenant ID
$clientSecret = getenv('AZURE_CLIENT_SECRET_VALUE'); // Optional. Azure Client Secret Value (Certificates & secrets)
$refreshToken = getenv('AZURE_REFRESH_TOKEN');

$mail = new PHPMailer(true);

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

   // Set OAuth2 token
   $mail->AuthType = 'XOAUTH2';
   $mail->setOAuth(new OAuth([
       'provider' => new Azure([
           'clientId' => $clientId,
           'tenantId' => $tenantId,
           'clientSecret' => $clientSecret
       ]),
       'clientId' => $clientId,
       'refreshToken' => $refreshToken,
       'clientSecret' => $clientSecret,
       'userName' => $email,
   ]));

   // Sender and recipient settings
   $mail->setFrom($email, 'Your Name'); // your office365 email
   $mail->addAddress('recipient@domain.com', 'Recipient Name');

   // HTML email content
   $mail->isHTML(true);  // Enable HTML mode
   $mail->Subject = 'Test HTML Email';
   $mail->Body    = '<h1>Welcome to Our Service!</h1><p>This is a <b>HTML</b> email sent using PHPMailer and OAuth2 authentication with Office 365 SMTP.</p>';
   $mail->AltBody = 'This is the plain-text version of the HTML email.';

   //Send email
   $mail->send();
   echo 'Message has been sent';
} catch (Exception $e) {
   echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

Quick breakdown:

If you need a more detailed tutorial, check the one in this link

Send email with an embedded image

Important note: Plain text emails don’t exactly support embedded images the same way HTML emails do. They lack the correct formatting capabilities like the <img> tag, which may affect the deliverability and accessibility of the email. 

Long story short, I’ll be using HTML email since it’s much more reliable. 

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\OAuth;
//@see https://github.com/greew/oauth2-azure-provider
use Greew\OAuth2\Client\Provider\Azure;

require 'vendor/autoload.php';

$email = getenv('AZURE_OFFICE365_EMAIL'); // your office365 email
$clientId = getenv('AZURE_CLIENT_ID'); // Azure Client ID
$tenantId = getenv('AZURE_TENANT_ID'); // Azure Tenant ID
$clientSecret = getenv('AZURE_CLIENT_SECRET_VALUE'); // Optional. Azure Client Secret Value (Certificates & secrets)
$refreshToken = getenv('AZURE_REFRESH_TOKEN');

$mail = new PHPMailer(true);

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

   // Set OAuth2 token
   $mail->AuthType = 'XOAUTH2';
   $mail->setOAuth(new OAuth([
       'provider' => new Azure([
           'clientId' => $clientId,
           'tenantId' => $tenantId,
           'clientSecret' => $clientSecret
       ]),
       'clientId' => $clientId,
       'refreshToken' => $refreshToken,
       'clientSecret' => $clientSecret,
       'userName' => $email,
   ]));

   // Sender and recipient settings
   $mail->setFrom($email, 'Your Name'); // your office365 email
   $mail->addAddress('recipient@domain.com', 'Recipient Name');

   // Embedding the image
   $mail->addEmbeddedImage('/path/to/image.jpg', 'image_cid');  // Replace with your image file path

   // HTML email content with the embedded image
   $mail->isHTML(true);  // Enable HTML mode
   $mail->Subject = 'Test Email with Embedded Image';
   $mail->Body    = '<h1>Hello!</h1><p>This is an email with an embedded image:</p><img src="cid:image_cid">'; // Reference the image using 'cid'
   $mail->AltBody = 'This is the plain-text version of the email with an embedded image.';

   //Send email
   $mail->send();
   echo 'Message has been sent';
} catch (Exception $e) {
   echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

Quick breakdown:

Common errors:

Send email using Outlook SMTP

Outlook SMTP works similarly to Office 365, but there are a few important differences in the server settings. Of course, Outlook SMTP is free and mostly for personal use, whereas Office 365 SMTP is geared towards business users. 

I’ll be covering the technical server specs, an exemplary code snippet, the main technical differences, and some troubleshooting tips.  

Here we go.

Server-specific technical details:

Note: I’ll keep using OAuth2 since it’s the most reliable method, but basic authentication may still work with Outlook. 

Code example:

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\OAuth;
//@see https://github.com/greew/oauth2-azure-provider
use Greew\OAuth2\Client\Provider\Azure;

require 'vendor/autoload.php';

$email = getenv('AZURE_OFFICE365_EMAIL'); // your office365 email
$clientId = getenv('AZURE_CLIENT_ID'); // Azure Client ID
$tenantId = getenv('AZURE_TENANT_ID'); // Azure Tenant ID
$clientSecret = getenv('AZURE_CLIENT_SECRET_VALUE'); // Optional. Azure Client Secret Value (Certificates & secrets)
$refreshToken = getenv('AZURE_REFRESH_TOKEN');

$mail = new PHPMailer(true);

try {
   // Configure PHPMailer for SMTP
   $mail->isSMTP();
   $mail->Host       = 'smtp-mail.outlook.com'; // instead of smtp.office365.com
   $mail->SMTPAuth   = true;
   $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
   $mail->Port       = 587;

   // Set OAuth2 token
   $mail->AuthType = 'XOAUTH2';
   $mail->setOAuth(new OAuth([
       'provider' => new Azure([
           'clientId' => $clientId,
           'tenantId' => $tenantId,
           'clientSecret' => $clientSecret
       ]),
       'clientId' => $clientId,
       'refreshToken' => $refreshToken,
       'clientSecret' => $clientSecret,
       'userName' => $email,
   ]));

   // Sender and recipient settings
   $mail->setFrom('your-email@outlook.com', 'Your Name');
   $mail->addAddress('recipient@domain.com', 'Recipient Name');

   // Plain-text email content
   $mail->isHTML(false);  // Disable HTML mode for plain-text
   $mail->Subject = 'Test Email Using Outlook SMTP';
   $mail->Body    = "This is a plain-text email sent using Outlook SMTP and OAuth2 authentication.";

   // Send email
   $mail->send();
   echo 'Message has been sent successfully' . PHP_EOL;
} catch (Exception $e) {
   echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}" . PHP_EOL;
}

Key technical differences between Office 365 and Outlook

SMTP hosts:

OAuth2 scopes:

Troubleshooting tips and tricks

  1. Authentication errors:
  1. Connection issues and timeouts:
  1. OAuth token errors:

Tip: If your email fails to reach the recipient, double-check the address validity and ensure it’s not picked up by spam filters. Also, keep a close eye on rate-limiting; personal Outlook accounts have a heavier rate limit than Office 365.

Microsoft 365 SMTP limitations

Microsoft imposes quite a few, sometimes confusing, limitations. So, I’ll break them down into three categories (technical limits, sending and rate limits, and authentication and security limits). This way it should be easier to decide whether Office 365 is the right choice for you. 

Technical limits

Sending and rate limits

Daily sending limit

Rate limit

Attachments limits 

Tip:  For those who send large volumes of emails, 100K a month or higher, it’s better to batch your messages or use an email service designed for bulk sending (such as Mailtrap or another SMTP service). The same goes if you need to handle large attachments. 

Security limitations: Multi-Factor Authentication (MFA) and phasing out legacy authentication

MFA requirement: 

Basic authentication deprecated:

Is there an alternative to Microsoft SMTP?

Of course, there’s an alternative — for me, that alternative is always Mailtrap Email API/SMTP. It’s part of the Mailtrap Email Delivery Platform and allows you to test, send, and control your emails. 

Okay, okay, I know it sounds like a blatant promo, but give me a moment to explain. 

I’ll cover the reasons to choose Mailtrap based on Office 365 limitations, then give you an exemplary PHPMailer snippet. And if you want to see the service in action right away, hit the play button below. 

Here are the reasons:

  1. Mailtrap SMTP seamlessly integrates with PHPMailer, allowing you to send emails without the complexities of configuring OAuth2 authentication. 
  1. If safety is the top priority (and it should be), Mailtrap supports TLS and SSL encryption. 
  1. You get access to advanced email analytics. This includes deliverability and open rates, click rates, bounce tracking, etc. Everything is packed into a helicopter-view dashboard so you can check the health of your campaigns at a glance. Plus, you’re one click away from drill-down reports for a more detailed overview. 
  1. With SMTP, you also get access to RESTful APIs and SDKs (PHP included). This allows for greater integration flexibility, especially if you want to scale the email infrastructure of your app or website. 
  1. Mailtrap features a visual drag-and-drop email template builder. It also allows you to quickly switch to HTML editing if need be. Of course, you can store, manage, and reuse the templates as you deem fit. 
  1. You get access to 24/7 human support. At Mailtrap, there’s a team of experts to address your questions and requests. Additionally, we have an in-house email deliverability expert who can, for example, assist you in transitioning to Mailtrap even if your infrastructure needs to support millions of emails a month. 
  1. You get access to Mailtrap Email Testing, which is a sandbox solution I’ll explain in detail in the following section. 

Now, I’ll give you an exemplary snippet to send emails via PHPMailer, using Mailtrap SMTP. 

Notes

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);

try {
    // SMTP configuration for Mailtrap
    $mail->isSMTP();
    $mail->Host       = 'live.smtp.mailtrap.io';
    $mail->SMTPAuth   = true;
    $mail->Username   = 'YOUR_MAILTRAP_USERNAME'; // Replace with your Mailtrap username
    $mail->Password   = 'YOUR_MAILTRAP_PASSWORD'; // Replace with your Mailtrap password
    $mail->SMTPSecure = 'tls'; // Use 'tls' or 'ssl' as required
    $mail->Port       = 587;  // Mailtrap SMTP port

    // Sender and recipient settings
    $mail->setFrom('your-email@example.com', 'Your Name');
    $mail->addAddress('recipient@example.com', 'Recipient Name');

    // Email content
    $mail->isHTML(true);
    $mail->Subject = 'Test Email via Mailtrap SMTP';
    $mail->Body    = '<h1>Hello!</h1><p>This is a test email sent using <b>Mailtrap SMTP</b> with PHPMailer.</p>';
    $mail->AltBody = 'This is the plain-text version of the email content';

    // Send email
    $mail->send();
    echo 'Message has been sent successfully via Mailtrap SMTP';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

Test emails and email sending on staging

Also part of the Mailtrap Email Delivery Platform, Mailtrap Email Testing provides a safe sandbox to test emails without the risk of sending them to your recipients. 

It helps devs and QA ensure their emails work as intended without affecting production environments. If you use API, you can seamlessly transition from testing to production once you’re happy with your templates. 

Note: Mailtrap Email Testing is available starting from the free plan (test 100 emails a month). 

I’ll cover the key features in greater detail soon. Again, you can hit the play button to see the PHPMailer testing in action and check the exemplary code snippet. 

Exemplary code snippet

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);

try {
    // SMTP configuration for Mailtrap (Testing/Sandbox)
    $mail->isSMTP();
    $mail->Host       = 'sandbox.smtp.mailtrap.io';  // Mailtrap SMTP server
    $mail->SMTPAuth   = true;
    $mail->Username   = 'YOUR_MAILTRAP_USERNAME';  // Mailtrap credentials
    $mail->Password   = 'YOUR_MAILTRAP_PASSWORD';
    $mail->SMTPSecure = 'tls';
    $mail->Port       = 2525;  // Mailtrap's standard port

    // Sender and recipient settings
    $mail->setFrom('your-email@example.com', 'Your Name');
    $mail->addAddress('recipient@example.com', 'Recipient Name');

    // Email content
    $mail->isHTML(true);
    $mail->Subject = 'Test Email in Sandbox with Mailtrap';
    $mail->Body    = '<h1>This is a test email</h1><p>Testing with <b>Mailtrap</b> in a sandbox environment.</p>';
    $mail->AltBody = 'This is a plain-text version of the email content';

    // Send email
    $mail->send();
    echo 'Test email sent successfully via Mailtrap';
} catch (Exception $e) {
    echo "Email could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

Key features:

In addition to the above, you also get the following:

Additional resources:

Wrapping up

I’ve walked through the complete process of PHPMailer Office 365 setup, including troubleshooting common issues and securing your email system with OAuth2. With these insights, you’re well-equipped to avoid or resolve common sending limitations like rate limits or authentication errors.

Even so, I hope you’ll give Mailtrap Email API/SMTP a try. If for no other reason then since the setup is simpler and you get advanced analytics 

Exit mobile version