How can HTML messages be properly sent using the mail() function in PHP?

When sending HTML messages using the mail() function in PHP, the message content needs to be properly formatted with the appropriate headers. To do this, you need to set the "Content-Type" header to "text/html" to indicate that the message is HTML-formatted. Additionally, make sure to properly escape any user input to prevent security vulnerabilities.

$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";

// Additional headers
$headers .= 'From: yourname@example.com' . "\r\n";

mail($to, $subject, $message, $headers);