What are some best practices for configuring and using PHPMailer for sending emails in PHP applications?

When configuring and using PHPMailer for sending emails in PHP applications, it is important to ensure that you set up the necessary parameters correctly, such as the SMTP host, port, username, and password. Additionally, it is recommended to enable SMTP debugging to troubleshoot any issues that may arise during email sending. It is also good practice to sanitize user input to prevent any potential security vulnerabilities.

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

require 'vendor/autoload.php';

// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);

try {
    //Server settings
    $mail->isSMTP();
    $mail->Host = 'smtp.example.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'your@example.com';
    $mail->Password = 'yourpassword';
    $mail->SMTPSecure = 'tls';
    $mail->Port = 587;

    //Recipients
    $mail->setFrom('from@example.com', 'Your Name');
    $mail->addAddress('recipient@example.com', 'Recipient Name');

    //Content
    $mail->isHTML(true);
    $mail->Subject = 'Subject';
    $mail->Body = 'Email body';

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