How can PHPMailer be optimized for efficient handling of form data and secure email transmission in a contact form setup?

To optimize PHPMailer for efficient handling of form data and secure email transmission in a contact form setup, you can sanitize and validate the form input data before sending it via PHPMailer. Additionally, you should enable SMTP authentication and use secure transport methods like SSL or TLS to encrypt the email transmission.

// Sanitize and validate form input data
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);

// Include PHPMailer library
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

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

// Enable SMTP authentication
$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 email content
$mail->setFrom($email, $name);
$mail->addAddress('recipient@example.com');
$mail->Subject = 'Contact Form Submission';
$mail->Body = $message;

// Send email
if($mail->send()) {
    echo 'Message sent successfully';
} else {
    echo 'Message could not be sent';
}