What are the best practices for handling SMTP authentication in PHP when using PHPMailer?

When using PHPMailer to send emails via SMTP, it is important to properly handle SMTP authentication to ensure secure and reliable email delivery. The best practice is to use SMTP authentication with a valid username and password to authenticate with the mail server. This helps prevent unauthorized access and ensures that emails are sent successfully.

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

// Include PHPMailer autoload file
require 'vendor/autoload.php';

// Instantiate PHPMailer
$mail = new PHPMailer();

// Set SMTP settings
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your_smtp_username';
$mail->Password = 'your_smtp_password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;

// Set other email parameters
$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
$mail->Subject = 'Test Email';
$mail->Body = 'This is a test email.';

// Send email
if ($mail->send()) {
    echo 'Email sent successfully.';
} else {
    echo 'Error sending email: ' . $mail->ErrorInfo;
}