Setting up PHPMailer with Office365 SMTP

JosephGarrone picture JosephGarrone · Jul 25, 2014 · Viewed 81.5k times · Source

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?

Answer

bgazzera picture bgazzera · Jan 11, 2017

@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';
}