How can PHP Mailer classes help prevent header injection in email forms?

PHP Mailer classes help prevent header injection in email forms by automatically sanitizing and validating email headers before sending the email. This prevents malicious users from injecting additional headers into the email, which can be used for spamming or phishing attacks.

use PHPMailer\PHPMailer\PHPMailer;

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

// Set email headers
$mail->From = 'from@example.com';
$mail->FromName = 'Your Name';
$mail->addAddress('recipient@example.com', 'Recipient Name');
$mail->Subject = 'Subject';
$mail->Body = 'Message body';

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