What are common pitfalls when sending form data via email using the mail() function in PHP?

Common pitfalls when sending form data via email using the mail() function in PHP include not properly sanitizing user input, not setting appropriate headers, and not handling errors effectively. To solve these issues, make sure to sanitize user input to prevent injection attacks, set headers such as From, Reply-To, and Content-Type correctly, and implement error handling to capture any issues that may arise during the email sending process.

// Sanitize user input
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);

// Set appropriate headers
$headers = "From: Your Name <youremail@example.com>\r\n";
$headers .= "Reply-To: $email\r\n";
$headers .= "Content-type: text/html\r\n";

// Send email
$mailSent = mail('recipient@example.com', 'Subject', $message, $headers);

// Check for errors
if($mailSent) {
    echo 'Email sent successfully.';
} else {
    echo 'Error sending email.';
}