March 5, 2019
PHP Mailer for Office 365
This might be little late, but still most of us are getting issue with sending email using PHP routing office 365. In this blog, just sharing one of my client issues where they were using PHP webpages and want to relay message through office 365. So, there PHP Mail for Office 365.
To configure the relay, we don’t need to do any configuration at Office 365 end. We just need to have one PHP mailer. Which we can get download from this link on github.
Once you download it, extract on your machine where PHP webpage has been hosted. On same folder, create a new file of PHP with below script.
<?php use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; require 'PHPMailer/src/Exception.php'; require 'PHPMailer/src/PHPMailer.php'; require 'PHPMailer/src/SMTP.php'; $mail = new PHPMailer(true); $mail->isSMTP(); $mail->Host = 'smtp.office365.com'; $mail->Port = 587; $mail->SMTPSecure = 'tls'; $mail->SMTPAuth = true; $mail->Username = 'admin@M365x895303.onmicrosoft.com'; $mail->Password = 'pdhewaju@12082'; $mail->SetFrom('admin@M365x895303.onmicrosoft.com', 'FromEmail'); $mail->addAddress('pdhewaju@outlook.com', 'ToEmail'); //$mail->SMTPDebug = 3; //$mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";}; //$mail->Debugoutput = 'echo'; //Attachments $mail->addAttachment('e:\readme.txt'); // Add attachments //$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name $mail->IsHTML(true); $mail->Subject = 'test email from PHP'; $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'; }
Once this is done, just try to send email.
2 Comments
Not able to connect as it says “SMTP Error: Could not authenticate.”. Also I checked few other blogs and it says Office365 Admin should do some settings.
https://docs.microsoft.com/en-us/Exchange/mail-flow-best-practices/how-to-set-up-a-multifunction-device-or-application-to-send-email-using-office-3?redirectSourcePath=%252farticle%252fHow-to-set-up-a-multifunction-device-or-application-to-send-email-using-Office-365-69f58e99-c550-4274-ad18-c805d654b4c4
I run in the same error and i fixed it by using port 25.