phplaraveloffice365

Send emails using Office365 integrated in laravel


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

Thank you guys in advance.


Solution

  • 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 = '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 '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.