Are there best practices for using PHPMailer with HTML forms?

When using PHPMailer with HTML forms, it is important to sanitize and validate user input to prevent security vulnerabilities such as SQL injection and cross-site scripting. Additionally, make sure to properly configure PHPMailer settings, such as SMTP server details and sender email address, to ensure successful email delivery. It is also recommended to handle form submission errors gracefully by displaying appropriate error messages to the user.

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Sanitize and validate form input
    $name = filter_var($_POST["name"], FILTER_SANITIZE_STRING);
    $email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
    $message = filter_var($_POST["message"], FILTER_SANITIZE_STRING);

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

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

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

        // Content
        $mail->isHTML(true);
        $mail->Subject = 'New message from your website';
        $mail->Body = "<p>Name: $name</p><p>Email: $email</p><p>Message: $message</p>";

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