What are common pitfalls to avoid when using the mail() function in PHP for sending emails?

One common pitfall to avoid when using the mail() function in PHP for sending emails is not properly sanitizing user input, which can leave your application vulnerable to email injection attacks. To prevent this, always validate and sanitize user input before using it in the mail() function. Additionally, make sure to set the "From" header properly to avoid emails being marked as spam.

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

// Set proper "From" header
$from = "From: Your Name <your_email@example.com>";

// Send email
$mail_success = mail($to, $subject, $message, $from);

if($mail_success) {
    echo "Email sent successfully";
} else {
    echo "Failed to send email";
}