Setting up PHPMailer with Office365 SMTP
@nitin's code was not working for me, as it was missing 'tls' in the SMTPSecure param.
Here is a working version. I've also added two commented out lines, which you can use in case something is not working.
<?php
require 'vendor/phpmailer/phpmailer/PHPMailerAutoload.php';
$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->Host = 'smtp.office365.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'YourPassword';
$mail->SetFrom('[email protected]', 'FromEmail');
$mail->addAddress('[email protected]', 'ToEmail');
//$mail->SMTPDebug = 3;
//$mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";}; //$mail->Debugoutput = 'echo';
$mail->IsHTML(true);
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
UPDATE: April 2020
Using the accepted answer for sending email using Office 365 has the high chance of not working since Microsoft is pushing for their Microsoft Graph (the only supported PHP framework right now is Laravel). If fortunately you were still able to make it work in your application, email will either go to the recipient's Junk, Trash, or Spam folder, which you don't want to happen.
Common errors I encountered were:
Failed to authenticate password. // REALLY FRUSTRATED WITH THIS ERROR! WHY IS MY PASSWORD WRONG?!
or
Failed to send AUTH LOGIN command.
or
Unable to send email using PHP SMTP. Your server might not be configured to send mail using this method.
In order to still make it work with the accepted answer, we just have to change a single line, which is the Password parameter line:
$mail->Password = 'YourOffice365Password';
Instead of setting the password with the one you use when you login to your Office365 account, you have to use an App Password instead.
Create App Password
First, in order to create an App Password, the Multi-Factor Authentication of your Office 365 account should be enabled (you may have to contact your administrator for this to be enabled).
After that, login your Office 365 in your favorite browser
- Go to My Account page (you will see the link to this page when you click your name's initials on the upper right)
- Choose Security & Privacy then Additional security verification
- At the top of the page, choose App Passwords
- Choose create to get an app password
- If prompted, type a name for your app password, and click Next
- You will then see the password generated by Office 365 as your App Password
- Copy the password
After copying the password, go back to your working code and replace the Password parameter with the copied password. Your application should now be able to properly send email using Office 365.
Reference:
Create an app password for Microsoft 365
Try this, it works fine for me, i have been using this for so long
$mail = new PHPMailer(true);
$mail->Host = "smtp.office365.com";
$mail->Port = 587;
$mail->SMTPSecure = '';
$mail->SMTPAuth = true;
$mail->Username = "email";
$mail->Password = "password";
$mail->SetFrom('email', 'Name');
$mail->addReplyTo('email', 'Name');
$mail->SMTPDebug = 2;
$mail->IsHTML(true);
$mail->MsgHTML($message);
$mail->Send();
UPDATE: May 2022
So i was struggling at this Problem really hard. For Business Accounts with Exchange Online and access to the Microsoft Admin Center i can provide the answer for this.
TLDR: Goto the Admin Center and select the User you want to send the Mail. Then look under settings after E-Mail and E-Mail Apps after the Setting "authenticated SMTP", simply enable it.
Still not working? I got you covered, here is how i got it fully working.
- Use PHP composer, saves a lot of work actually.
- Replace your Code with my Code and change it after test
<?php
//Import the PHPMailer class into the global namespace
use PHPMailer\PHPMailer\PHPMailer; //important, on php files with more php stuff move it to the top
use PHPMailer\PHPMailer\SMTP; //important, on php files with more php stuff move it to the top
//SMTP needs accurate times, and the PHP time zone MUST be set
//This should be done in your php.ini, but this is how to do it if you don't have access to that
date_default_timezone_set('Etc/UTC');
require 'path/to/vendor/autoload.php'; //important
//Enable SMTP debugging
// SMTP::DEBUG_OFF = off (for production use)
// SMTP::DEBUG_CLIENT = client messages
// SMTP::DEBUG_SERVER = client and server messages
//$mail->SMTPDebug = SMTP::DEBUG_off;
//SMTP
$mail = new PHPMailer(true); //important
$mail->CharSet = 'UTF-8'; //not important
$mail->isSMTP(); //important
$mail->Host = 'smtp.office365.com'; //important
$mail->Port = 587; //important
$mail->SMTPSecure = 'tls'; //important
$mail->SMTPAuth = true; //important, your IP get banned if not using this
//Auth
$mail->Username = '[email protected]';
$mail->Password = 'your APP password';//Steps mentioned in last are to create App password
//Set who the message is to be sent from, you need permission to that email as 'send as'
$mail->SetFrom('[email protected]', 'Hosting Group Inc.'); //you need "send to" permission on that account, if dont use [email protected]
//Set an alternative reply-to address
$mail->addReplyTo('[email protected]', 'First Last');
//Set who the message is to be sent to
$mail->addAddress('[email protected]', 'SIMON MÜLLER');
//Set the subject line
$mail->Subject = 'PHPMailer SMTP test';
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->msgHTML(file_get_contents('replace-with-file.html'), __DIR__); //you can also use $mail->Body = "</p>This is a <b>body</b> message in html</p>"
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
//Attach an image file
//$mail->addAttachment('../../../images/phpmailer_mini.png');
//send the message, check for errors
if (!$mail->send()) {
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
}
- This may looks like your file, whats ok, but now comes the easy-tricky part. As like as Google, Microsoft implemented a "switch" for the SMTP stuff. Simply go to your Admin Center from your Business Account, or kindly ask someone with permission to do that part:
- navigate to https://admin.microsoft.com/AdminPortal/Home#/users
- select to user where you want to send the email from
- under the tab "E-Mail" search for "E-Mail-Apps", click on "manage E-Mail-Apps"
- here you can select "authenticated SMTP", make sure that option is checked and save the Changes
if you use MFA, then make sure you use an app password as mentioned in https://stackoverflow.com/a/61359150/14148981
Run the script
I hope this helps someone. Took me hell long to find this option on myself.
Summary of all steps to get App password and authentication ON:
- With Admin Account:
- Active Directory AD -> Properties -> Security Default: Turn OFF.
- Active directory Portal -> conditional access -> Configure MFA Trusted IPs -> Allow user App password: Enable
- Admin Page User List -> 'Multi factor Authentication' for target user: Enable then Enforce
- Admin Page User List -> User details -> Mail -> 'Manage Email Apps' -> 'Authenticated SMTP': Enable
- With user account:
- User Account Profile -> Security -> add login method: App Password
- PHP Mailer Settings:
- smtp.office365.com, 587, tls, email, appPassword