What potential security risks are associated with using the mail() function in PHP web forms?

The potential security risks associated with using the mail() function in PHP web forms include the possibility of email header injections, spamming, and unauthorized sending of emails. To mitigate these risks, it is important to properly sanitize and validate user input before using it in the mail() function.

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

// Check if the email address is valid
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    // Proceed with sending the email
    $to = "recipient@example.com";
    $subject = "Contact Form Submission";
    $headers = "From: $name <$email>";

    // Send the email
    mail($to, $subject, $message, $headers);
    echo "Email sent successfully.";
} else {
    echo "Invalid email address.";
}