Home » Php » php – PHPmailer not connecting to office365 SMTP

php – PHPmailer not connecting to office365 SMTP

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have a script that uses phpmailer to send emails via office 365 smtp. It had been working for the last year or so. Now I’m getting an error connecting to the server.

PHP Fatal error:  Uncaught PHPMailer\PHPMailer\Exception: SMTP Error: Could not connect to SMTP host. in C:\inetpub\wwwroot\Parishes_staging\ChristTheKing\vendor\phpmailer\phpmailer\src\PHPMailer.php:1898
Stack trace:
#0 C:\inetpub\wwwroot\Parishes_staging\ChristTheKing\vendor\phpmailer\phpmailer\src\PHPMailer.php(1725): PHPMailer\PHPMailer\PHPMailer->smtpConnect(Array)
#1 C:\inetpub\wwwroot\Parishes_staging\ChristTheKing\vendor\phpmailer\phpmailer\src\PHPMailer.php(1481): PHPMailer\PHPMailer\PHPMailer->smtpSend('Date: Fri, 14 F...', 'This is a multi...')
#2 C:\inetpub\wwwroot\Parishes_staging\ChristTheKing\vendor\phpmailer\phpmailer\src\PHPMailer.php(1320): PHPMailer\PHPMailer\PHPMailer->postSend()
#3 C:\inetpub\wwwroot\Parishes_staging\ChristTheKing\submitform2.php(195): PHPMailer\PHPMailer\PHPMailer->send()
#4 {main}
thrown in C:\inetpub\wwwroot\Parishes_staging\ChristTheKing\vendor\phpmailer\phpmailer\src\PHPMailer.php on line 1898

The script is as follows:

require 'vendor/autoload.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 = "password";                           
$mail->SetFrom('[email protected]', 'FromEmail');
//$mail->addAddress('[email protected]', 'ToEmail');
$mail->addAddress('[email protected]', 'ToEmail');
$mail->addBCC('[email protected]', 'ToBCCEmail');
$mail->SMTPDebug  = 3;
$mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";}; 
$mail->Debugoutput = 'echo';
$mail->IsHTML(true);

$mail->Subject = 'Parish Registration Form';
$mail->Body    = $body;
$mail->AltBody = $body;

if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} 
else {
    echo 'Message has been sent';
}

I’ve searched the internet for the connection settings associated with Office 365 and I see nothing wrong. Did something change on the Microsoft servers that I should know about but don’t?

How to&Answers:

There is nothing wrong on your end.

Check your firewall for port 587 blocking. If not then the issue might be from SMTP server-side. Contact Microsoft support.

Answer:

It turns out to be a certificate error. When no certificate file is specified in php.ini the root certificate is supposed to be used. but it was not being used.

I had to add the following code to get it working:

$mail->SMTPOptions = array(
    'ssl' => array(
    'verify_peer' => false,
    'verify_peer_name' => false,
    'allow_self_signed' => true
    )
);