Setting up PHPMailer with Office365 SMTP
Asked Answered
H

10

30

I am attempting to set up PHPMailer so that one of our clients is able to have the automatically generated emails come from their own account. I have logged into their Office 365 account, and found that the required settings for PHPMailer are:

Host: smtp.office365.com
Port: 587
Auth: tls

I have applied these settings to PHPMailer, however no email gets sent (The function I call works fine for our own mail, which is sent from an external server (Not the server serving the web pages)).

"host"      => "smtp.office365.com",
"port"      => 587,
"auth"      => true,
"secure"    => "tls",
"username"  => "[email protected]",
"password"  => "clientpass",
"to"        => "myemail",
"from"      => "[email protected]",
"fromname"  => "clientname",
"subject"   => $subject,
"body"      => $body,
"altbody"   => $body,
"message"   => "",
"debug"     => false

Does anyone know what settings are required to get PHPMailer to send via smtp.office365.com?

Halima answered 25/7, 2014 at 3:14 Comment(4)
what s the phpmail error function return ?Claret
@Dagon Nothing, my apache crashes and starts serving on ports 43 and 56252 or something near there.Halima
Your settings look fine, but you need to see error codes or we can't help you, and it helps if you post your actual code. Eliminate Apache from your tests - run a script from a command line and set SMTPDebug = 3 to get an SMTP transcript. Office 365 SMTP is unreliable - I've several reports of it failing.Lionize
One other thing to check is that your smtp server is actually turned on, otherwise php won't be able to send any emails via smtp. Eg. if you are using postfix in debian/ubuntu: ps aux | grep postfix and if you get no output: sudo /etc/init.d/postfix start. You can also view undelivered emails like so: sudo mailq. This will be empty if the emails are being sent.Vaccine
W
34

@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';
}
Widera answered 11/1, 2017 at 13:45 Comment(8)
Hi, this code is not working for me. When I enable debug it says: "SMTP -> ERROR: Password not accepted from server: " I obviously double checked the credentials.Instructions
this worked for me, the issue was I was missing STMPSecure = 'tls', thanks!Exothermic
DO NOT DO THIS. Currently (Aug & Sept 2018) any email sent using the Microsoft office SMTP server will go into junk on the recipient's side if they to use 365 to host their emails. There is nothing you can do to stop this, even if the recipient declares your emails as not junk until they are blue in the face, they will still always go to junk. This obviously has nothing to do with Microsoft wanting you to use Graph (cough, cough), which by the way is foolishly limited to email sizes of 4mb (face palm).Hydroelectric
I've tried this and it works in March 2020. This is an existing account I am using this with, and not a bogus do-not-reply from-address.Pimply
@JustinLevene you are saying not to you use this without suggesting an alternative... (facepalm)Riggins
@Xsmael, read the comment, I mentioned Graph as this is the only choice. There is obviously no way to circumvent a process within the Microsoft closed realm, unless you are Microsoft... (facepalm).Hydroelectric
@JustinLevene alright i get it now. It was not clear to me as you used sarcasm to say it in your first comment. I missed it! (facepalm)Riggins
This is Working For me actually. but When we need to send the email from a group email , We don't have passwords for those emails.those are just emails without passwords. How can we achive that ?Quinsy
F
23

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.

  1. Use PHP composer, saves a lot of work actually.
  2. 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 {
}
  1. 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
  1. if you use MFA, then make sure you use an app password as mentioned in https://mcmap.net/q/479249/-setting-up-phpmailer-with-office365-smtp

  2. 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:

  1. 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
  1. With user account:
  • User Account Profile -> Security -> add login method: App Password
  1. PHP Mailer Settings:
  • smtp.office365.com, 587, tls, email, appPassword
Foudroyant answered 23/8, 2020 at 19:21 Comment(3)
If you use Office 365 via GoDaddy, you have no Microsoft 'Admin' page, but a GoDaddy page where you manage this setting. Instructions on how to switch it on or off can be found here: Enable SMTP AuthenticationMellins
Fatal error: Uncaught PHPMailer\PHPMailer\Exception: SMTP Error: Could not connect to SMTP host. Connection failed. stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages: error:1416F086:SSL routines:tls_process_server_certificate:certificate verify failed in C:\xampp\htdocs\vendor\phpmailer\phpmailer\src\PHPMailer.php:2199Schmaltzy
@simonmüller I have used relay service of office 365 but I am still getting errorJereme
P
11

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

Perceptible answered 22/4, 2020 at 7:6 Comment(6)
Thank you. I have just migrated two clients over to phpMailer from standard sendMail and both client utilise 365 cloud email. Neither are working so I can only assume they both need app passwords created. I have passed these requests on to their email IT guy to set up.Culmiferous
Hi. I have setup my App Password on Office 365 but it still doesn't work. It says password command failed. Any ideas?Slyke
Nice dude, all i had to do was to create an app on my address.Danielson
June 2022, I just sent an email connected to Office 365 (smtp.office365.com) with phpmailer 6.6.3 / php 8.1 with no problems. The message even arrived in the normal inbox of my Yahoo! Mail.Allopathy
@FellipeSanches I can't find App Passwords...I have no idea how to get there. Additional security verification page does not have a link to app passwords. Any idea how to get there?Vaso
@Vaso I didn't set the app password, the only requirement I have to succeed was to use updated versions of php and phpmailer, because with php 5 and phpmailer 5 I couldn't authenticate in Office 365. TLS parameter must also be true in phpmailer.Allopathy
D
4

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();
Droughty answered 7/6, 2016 at 6:0 Comment(0)
S
3

I had the same issue when we moved from Gmail to Office365.

You MUST set up a connector first (either an open SMTP relay or Client Send). Read this and it will tell you everything you need to know about allowing Office365 to send email:

https://technet.microsoft.com/en-us/library/dn554323.aspx

Scanlon answered 30/4, 2015 at 8:55 Comment(2)
Hmm I did all the steps, but I still get SMTP: connect failsWarrantor
Ok, the relay is set, but the only way I could make it work was to use the original smtp.office365.com port 587 with tls. The instructions were saying to use the target of the MX entry... it was wrong.Warrantor
T
1

Update: Dec 2020

I resolved the problem by NOT setting the App Password and MFA(Disable it!).

I did it by disabling MS security default at

  • Microsoft 365 admin center
  • Azure Active Directory admin center
  • Azure Active Directory
  • Properties
  • Manage Security defaults
  • Enable Security defaults
  • No

When it's set, send email with your Office365 username(Email Address) and password (Not App Password)

Tattletale answered 15/12, 2020 at 6:21 Comment(2)
Here you disabled all the "security defaults". Would you possibly know disabling which default option exactly made it work? Ideally, we'd be able to tweak exactly that one option and let the security defaults stay on - for our security. :)Tessietessier
It is "EASIER" to turn off security, but that doesn't mean it is better. The best practice would be to use App Password and MFA, even though it is harder to get it to work. However, to help users understand the ramifications of turning off Security Defaults, it basically just turns on Multi-Factor Authentication (MFA) for all accounts. When you turn off security defaults, you can then manage MFA separately on each account. You can enable MFA on most accounts and disable it on the account used to send mail from your app. Hopefully this answers @Tessietessier question.Ridge
Y
1

Update september 2021

As of September 2022 (so from now on only a year) Microsoft will deprecating and shut down what they call basic authentication. That includes, but is not limited to, SMTP. They later announced that tenant administrators will be able to re-enable SMTP_AUTH, but (in my opinion) it opens up the door for permanently disabling it in the feature.

For now, Microsoft is not disabling it, but they encourage you to authenticate on different ways. On the documentation site they placed a warning telling you this.

Today I will do some research on how to use this new methods. For my application (PHP, CodeIgniter) I found this Microsoft package. I'm going to try sending my mails using this package, I hope this will be a smooth experience, but I'm afraid it will be a hell of a ride... I'll keep you all posted.

Youngstown answered 28/9, 2021 at 8:16 Comment(2)
did you able to find the solution?Pyrolysis
I managed to change my whole application workflow. It was a lot of work, and I still don't know all the things I changed and why it works but my application is now using the Microsoft Graph API.Youngstown
S
1

I was facing this error during configuration of PHPMailer 5.2 stable with outlook SMTP. I found this:

SMTP ERROR:

  • Password command failed, Authentication unsuccessful, SmtpClientAuthentication is disabled for the Tenant.

  • SMTP connect() failed.

After some research I have resolved this issue by enabling the Authenticated SMTP

Use the Microsoft 365 admin center to enable or disable SMTP AUTH on specific mailboxes

  1. Open the Microsoft 365 admin center and go to Users > Active users.
  2. Select the user, and in the flyout that appears, click Mail.
  3. In the Email apps section, click Manage email apps.
  4. Verify the Authenticated SMTP setting: unchecked = disabled, checked = enabled.
  5. When you're finished, click Save changes.
Shellacking answered 20/1, 2022 at 19:30 Comment(0)
S
1

I modified the example in the current PHPmailer version 6.5.4 to allow for Microsoft 365 non auth TLS connection (ie you do not need to use an license user account but can use a shared mailbox as the sender)

$mail = new PHPMailer(true);

try {

    //Enable SMTP debugging
    // $mail->SMTPDebug = 3;  // connection, client and server level debug!

    //SMTP
    $mail->CharSet = 'UTF-8'; 
    $mail->isSMTP();  
    $mail->Host = 'domain-xyz.mail.protection.outlook.com';
    $mail->Port       = 25; 
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;  //Enable implicit TLS encryption
    $mail->SMTPAuth   = false;  
    // as advised OPTION #3 on this page
    // https://learn.microsoft.com/en-us/exchange/mail-flow-best-practices/how-to-set-up-a-multifunction-device-or-application-to-send-email-using-microsoft-365-or-office-365 

    //Auth
    $mail->Username = '[email protected]';
    $mail->Password = 'yourpassword';    // set SMTPAuth to false though right so this is not used?

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    //you need permission to that email as 'send as'
    $mail->SetFrom('website@[email protected]', 'Website'); 
    $mail->addReplyTo('website@[email protected]', 'Website');


    // Sending to a external recipient
    $mail->addAddress('[email protected]', 'John doe');

    $mail->Subject = 'PHPMailer TESTY TEST';
    
    $mail->isHTML(true); 
    $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('img/logo.png');

    //send the message, check for errors
    $mail->send();
    echo 'Message has been sent';
    
}  catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
Subjunction answered 25/2, 2022 at 13:22 Comment(0)
B
-1

You need an App Password and multi-factor authentication enabled to able to send mails from third party applications using office365 stmp. Google it for further information

Billingsgate answered 28/11, 2019 at 7:59 Comment(1)
Your answer ("need an App Password and multi-factor authentication enabled") isn't always required. That is only one of the optional ways to configure Office 365 to send email from a third party app. And your explanation to "Google it" is not helpful. Other answers referred to this reference: learn.microsoft.com/en-us/exchange/mail-flow-best-practices/…. That document can help you decide if your setup should use App Password or not.Ridge

© 2022 - 2024 — McMap. All rights reserved.