What are some common pitfalls to avoid when sending emails using PHP's mail function?

One common pitfall to avoid when sending emails using PHP's mail function is not properly sanitizing user input, which can lead to security vulnerabilities such as email header injection. To prevent this, always validate and sanitize user input before using it in the email headers. Another pitfall is not handling errors or exceptions properly, which can result in emails not being sent or important information being lost. Make sure to check for errors and handle them gracefully to ensure reliable email delivery.

// Sanitize user input before using it in email headers
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);

// Handle errors or exceptions when sending emails
if (mail($email, 'Subject', 'Message')) {
    echo 'Email sent successfully';
} else {
    echo 'Failed to send email';
}