What are the recommended practices for sending emails in PHP, especially when dealing with dynamic content like database query results?

When sending emails in PHP with dynamic content like database query results, it's recommended to use a templating system to separate the email content from the PHP code. This helps maintain clean and readable code, as well as making it easier to update the email content in the future without changing the PHP logic.

// Example using PHPMailer library for sending emails with dynamic content

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php'; // Include PHPMailer library

// Create a new PHPMailer instance
$mail = new PHPMailer();

// Set up the email parameters
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@example.com';
$mail->Password = 'yourpassword';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;

$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');

// Load the email template from a file
$emailContent = file_get_contents('email_template.html');

// Replace placeholders in the template with dynamic content
$emailContent = str_replace('{name}', $name, $emailContent);
$emailContent = str_replace('{message}', $message, $emailContent);

$mail->isHTML(true);
$mail->Subject = 'Subject line';
$mail->Body = $emailContent;

// Send the email
if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}