How to Send Email Using SMTP in PHP | Step-by-Step Guide

Learn how to send email using SMTP in PHP with this step-by-step guide. We'll show you how to use PHPMailer to send email via SMTP, and provide example code to get you started.

To send an email using SMTP in PHP, you can use the built-in PHPMailer class. Here's an example of how to use PHPMailer to send an email using SMTP:

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

// Create a new PHPMailer instance
$mail = new PHPMailer(true);

try {
    //Server settings
    $mail->SMTPDebug = 0;                                 // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'smtp.example.com';                     // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'yourusername';                     // SMTP username
    $mail->Password = 'yourpassword';                     // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('[email protected]', 'Mailer');
    $mail->addAddress('[email protected]', 'Recipient');     // Add a recipient

    //Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = 'Subject';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the plain text version of the email body for non-HTML email clients.';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo 'Message could not be sent. Error: ', $mail->ErrorInfo;
}

Note that in this example, we assume you have already installed PHPMailer using Composer. If you haven't, you can install it by running the following command in your terminal:

composer require phpmailer/phpmailer

Also, make sure to replace the SMTP server details, username, and password with your own SMTP server details, username, and password.