15

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"  => "clientemail@office365.com",
"password"  => "clientpass",
"to"        => "myemail",
"from"      => "clientemail@office365.com",
"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?

JosephGarrone
  • 3,614
  • 2
  • 31
  • 59
  • 1
    what s the phpmail error function return ? –  Jul 25 '14 at 03:38
  • @Dagon Nothing, my apache crashes and starts serving on ports 43 and 56252 or something near there. – JosephGarrone Jul 25 '14 at 03:39
  • 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. – Synchro Jul 25 '14 at 05:42
  • 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. – mulllhausen Sep 14 '16 at 04:00

7 Answers7

27

@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 = 'somebody@somewhere.com';
$mail->Password = 'YourPassword';
$mail->SetFrom('somebody@somewhere.com', 'FromEmail');
$mail->addAddress('recipient@domain.com', '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';
}
bgazzera
  • 386
  • 3
  • 3
  • 4
    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. – Rafael Sisto Apr 19 '17 at 17:42
  • this worked for me, the issue was I was missing STMPSecure = 'tls', thanks! – Lorenzo Meriggi Aug 01 '17 at 11:51
  • 1
    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). – Justin Levene Sep 11 '18 at 18:18
  • 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. – SurfMan Mar 19 '20 at 08:59
8

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

Logan Wayne
  • 5,884
  • 15
  • 29
  • 47
  • 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. – Scott Richardson May 21 '20 at 03:27
  • Hi. I have setup my App Password on Office 365 but it still doesn't work. It says `password command failed`. Any ideas? – xjshiya Jun 24 '20 at 01:49
  • Nice dude, all i had to do was to create an app on my address. – Dezz H Oct 20 '20 at 16:08
6

UPDATE: August 2020

So i was struggeling 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 = 'yourname@mail.org';
$mail->Password = 'yourpassword';

//Set who the message is to be sent from, you need permission to that email as 'send as'
$mail->SetFrom('hosting@mail.org', 'Hosting Group Inc.'); //you need "send to" permission on that account, if dont use yourname@mail.org

//Set an alternative reply-to address
$mail->addReplyTo('no-reply@mail.com', 'First Last');

//Set who the message is to be sent to
$mail->addAddress('customer@othermail.com', '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://stackoverflow.com/a/61359150/14148981

  2. Run the script

I hope this helps someone. Took me hell long to find this option on myself.

Simon Müller
  • 73
  • 1
  • 4
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();
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

  • Hmm I did all the steps, but I still get SMTP: connect fails – Sebas Sep 17 '15 at 03:30
  • 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. – Sebas Sep 17 '15 at 04:17
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

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)

BadLeo
  • 405
  • 4
  • 11