How can PHPMailer be used to prevent header injection in email forms?

Header injection in email forms can be prevented by using PHPMailer's built-in methods for setting headers safely. By using PHPMailer's setFrom() and addAddress() methods to set the sender and recipient addresses, you can prevent malicious users from injecting additional headers into the email. Additionally, using PHPMailer's clearAllRecipients() method before adding new recipients can help ensure that only intended recipients receive the email.

use PHPMailer\PHPMailer\PHPMailer;

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

// Set the sender address using setFrom() method
$mail->setFrom('sender@example.com', 'Sender Name');

// Add recipient address using addAddress() method
$mail->addAddress('recipient@example.com', 'Recipient Name');

// Clear all recipients before adding new ones
$mail->clearAllRecipients();