What are common pitfalls when sending emails using PHP and how can they be avoided?

Common pitfalls when sending emails using PHP include not properly setting headers, using incorrect email addresses, and not handling errors effectively. To avoid these pitfalls, make sure to set the necessary headers, validate email addresses before sending, and implement error handling to catch any issues that may arise.

// Example of setting headers, validating email address, and error handling
$to = "recipient@example.com";
$subject = "Test email";
$message = "This is a test email.";

$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=ISO-8859-1\r\n";

if(filter_var($to, FILTER_VALIDATE_EMAIL)) {
    if (mail($to, $subject, $message, $headers)) {
        echo "Email sent successfully";
    } else {
        echo "Failed to send email";
    }
} else {
    echo "Invalid email address";
}