phpmailer with Office 365 smtp

Posted under » PHP on 13 October 2025

Before whatsapp, there was email. One of the first use of PHP that I've learnt is to create a feedback form which send an email. There was a PERL version but no longer popular.

PHPMailer is great for sending mails. To install, use composer

composer require phpmailer/phpmailer

You will see a 'vendor' folder being created. To create a mailer,

<¿php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php'; // Adjust the path as needed if you`re not using Composer

$mail = new PHPMailer(true); // instantiate 1st

try {
    //Server settings
    $mail->isSMTP();                                            // Send using 365 SMTP
    $mail->Username   = 'your_email@example.com';               // SMTP username
    $mail->Password   = 'your_password';                        // SMTP password
    $mail->Host = "smtp.office365.com";
    $mail->Port = 587;
    $mail->SMTPSecure = 'tls';
    $mail->SMTPAuth = true;

    // Sender and recipient settings
    $mail->setFrom('info@anoneh.io', 'anoneh');
    $mail->addReplyTo('info@anoneh.io', 'anoneh');
    $mail->addAddress('recipient1@gmail.com', 'Tom'); // Primary recipient
    // CC and BCC
    $mail->addCC('cc1@example.com', 'Elena');
    $mail->addBCC('bcc1@example.com', 'Alex');

    // Email content
    $mail->isHTML(true); // Set email format to HTML
    $mail->Subject = "PHPMailer SMTP test";
    $mail->Body = '<h1>Send HTML Email using SMTP in PHP</h1><p>This is
    a test email I`m sending using SMTP mail server with PHPMailer.</p>';
    $mail->AltBody = 'This is the plain text version of the email content';

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

If you want to send a list of people, you can use associative array eg. Add a 1 second pause when the list is long or like more than a hundred.

$pelajar = array('surai@gmail' => 'OHI SURAIA JAHAN', 'aedenng@gmail.com' => 'AEDEN XANDER');
foreach ($pelajar as $username => $nama)
{ //To email address and name
   $mail->addAddress($username, $nama );
   sleep(1);
}


web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data