What are common pitfalls when sending form data via PHP mail function?

Common pitfalls when sending form data via PHP mail function include not properly sanitizing user input, not validating input data, and not handling potential errors in the mail function. To solve these issues, always sanitize and validate user input to prevent injection attacks, check for errors when sending the email, and provide proper error handling.

<?php
// Sanitize and validate form data
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);

// Check if email is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Invalid email format";
    exit;
}

// Send email
$to = "recipient@example.com";
$subject = "Contact Form Submission";
$message = "Name: $name\nEmail: $email";
$headers = "From: $email";

if (mail($to, $subject, $message, $headers)) {
    echo "Email sent successfully";
} else {
    echo "Failed to send email";
}
?>