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

Common pitfalls when sending HTML emails using the mail() function in PHP include not setting the appropriate headers for HTML content, not properly encoding the HTML content, and not handling errors or exceptions gracefully. To address these issues, make sure to set the Content-Type header to indicate HTML content, properly encode the HTML content using functions like htmlspecialchars(), and implement error handling to catch any issues that may arise during the email sending process.

$to = "recipient@example.com";
$subject = "HTML Email Test";
$message = "<html><body><h1>Hello, this is a test email!</h1></body></html>";

$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

// Encode the HTML content
$message = htmlspecialchars($message);

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