What potential security risks are associated with using PHPMailer for contact forms on websites?

PHPMailer is prone to email header injection attacks if user input is not properly sanitized before being passed to the mail function. To mitigate this risk, always validate and sanitize user input before using it in the email headers.

// Sanitize user input before using it in the email headers
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);

// Create a new PHPMailer instance
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);

// Set email parameters
$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
$mail->Subject = 'Contact Form Submission';
$mail->Body = "Name: $name\nEmail: $email\nMessage: $message";

// Send the email
$mail->send();