What are best practices for defining and using header variables when sending HTML emails in PHP?
When sending HTML emails in PHP, it is important to define and use header variables correctly to ensure proper delivery and formatting. Best practices include setting the Content-Type header to indicate that the email contains HTML content, setting the charset to UTF-8 for proper encoding, and including additional headers like From, Reply-To, and MIME-Version.
<?php
$to = "recipient@example.com";
$subject = "HTML Email Test";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= "From: sender@example.com" . "\r\n";
$headers .= "Reply-To: reply@example.com" . "\r\n";
$message = "<html><body>";
$message .= "<h1>Hello, this is a test HTML email</h1>";
$message .= "<p>This is a paragraph in the email body.</p>";
$message .= "</body></html>";
mail($to, $subject, $message, $headers);
?>