Send emails using Office365 integrated in laravel

15,706

you can use below php code to send emails using Office365

<?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 'Email could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Email has been sent.';
}

You can uncomment the commented code in case you receive any error.

You can also use Swift Mailer library in Laravel to send emails. The .env file should contain as default the following values:

MAIL_DRIVER=null
MAIL_HOST=null
MAIL_PORT=null
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

These are the default values, you need to replace it with your Office365 details like below :

MAIL_DRIVER=smtp
MAIL_HOST=smtp.office365.com
MAIL_PORT=587
MAIL_USERNAME=Office365AccountEmail
MAIL_PASSWORD=Office365AccountPassword
MAIL_ENCRYPTION=tls

For more details you can refer this link

Hope this will help you.

Share:
15,706
Jeric
Author by

Jeric

Full Stack Developer (Back End &amp; Front End Developer) Programming Languages Known: PHP, Laravel Framework, VB .net, C#, Ruby on Rails Others: Javascript, JQuery, Ajax, vuejs, CSS3, HTML5, HAML

Updated on June 13, 2022

Comments

  • Jeric
    Jeric almost 2 years

    Just want to know if how can I use Office365 integrated in laravel on sending emails.

    Thank you guys in advance.