How can PHP be used to send HTML emails with correct formatting and display in mail clients?

When sending HTML emails using PHP, it is important to ensure that the email is correctly formatted and displays properly in various mail clients. To achieve this, the HTML content of the email should be properly structured with inline CSS styles for consistent rendering. Additionally, the email headers should include the necessary MIME type and content type declarations to indicate that the email contains HTML content.

<?php
$to = "recipient@example.com";
$subject = "HTML Email Test";
$message = "
<html>
<head>
<style>
  body {
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
    color: #333;
  }
</style>
</head>
<body>
<h1>Hello!</h1>
<p>This is a test email with HTML content.</p>
</body>
</html>
";

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

// Additional headers
$headers .= 'From: Your Name <youremail@example.com>' . "\r\n";

// Send email
mail($to, $subject, $message, $headers);
?>