What are the best practices for handling email content generation in PHP?

When generating email content in PHP, it is important to ensure that the email is properly formatted and contains relevant information. One best practice is to use HTML templates to structure the email content, making it easier to customize and maintain. Additionally, sanitizing user input and using proper encoding techniques can help prevent security vulnerabilities in the email content.

// Example code snippet for generating email content in PHP using HTML template

$emailTemplate = '<html><body><h1>Hello, {name}!</h1><p>This is a sample email content.</p></body></html>';

// Replace placeholders with dynamic data
$name = 'John Doe';
$emailContent = str_replace('{name}', $name, $emailTemplate);

// Send email
$to = 'recipient@example.com';
$subject = 'Sample Email';
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: sender@example.com' . "\r\n";

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