What are the potential security risks associated with using user input directly in PHP mail functions?

Using user input directly in PHP mail functions can lead to security risks such as email injection attacks, where malicious users can inject additional email headers or content into the email being sent. To mitigate this risk, it is important to sanitize and validate user input before using it in mail functions.

// Sanitize and validate user input before using it in PHP mail function
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);

// Use a library like PHPMailer to send the email securely
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

$mail = new PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@example.com';
$mail->Password = 'yourpassword';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;

$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress($email);

$mail->isHTML(true);
$mail->Subject = 'Subject';
$mail->Body = 'Email body';

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}