How can one effectively incorporate HTML code from a text field into the message body of an email using PHP?

When incorporating HTML code from a text field into the message body of an email using PHP, it is important to sanitize the input to prevent any potential security vulnerabilities. One way to do this is by using the htmlspecialchars() function to convert special characters to HTML entities. This will ensure that the HTML code is displayed correctly in the email without any harmful effects.

// Get HTML code from text field
$htmlCode = $_POST['html_code'];

// Sanitize the HTML code
$sanitizedHtml = htmlspecialchars($htmlCode);

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

// Send email with sanitized HTML code
mail('recipient@example.com', 'Subject', $sanitizedHtml, $headers);