What are common pitfalls when using PHP mail functions and how can they be avoided?

Common pitfalls when using PHP mail functions include not properly setting headers, not sanitizing user input, and not handling errors gracefully. To avoid these pitfalls, always set headers correctly, validate and sanitize user input before using it in the email, and implement error handling to catch any issues that may arise.

// Example of setting headers correctly, sanitizing user input, and error handling
$to = "recipient@example.com";
$subject = "Test Email";
$message = "This is a test email.";

// Set headers
$headers = "From: sender@example.com \r\n";
$headers .= "Reply-To: sender@example.com \r\n";
$headers .= "MIME-Version: 1.0 \r\n";
$headers .= "Content-type: text/html; charset=utf-8 \r\n";

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

// Send email
if(mail($to, $subject, $message, $headers)){
    echo "Email sent successfully!";
} else {
    echo "Email sending failed. Please try again.";
}