What is the recommended method for formatting and sending email content in PHP scripts?

When sending email content in PHP scripts, it is recommended to use the PHPMailer library for better control and security. PHPMailer allows you to easily format and send emails with attachments, HTML content, and more. It also helps prevent common email vulnerabilities such as header injection.

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

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

// 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 = 'ssl';
$mail->Port = 465;

$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
$mail->isHTML(true); // Set email format to HTML

$mail->Subject = 'Subject of the Email';
$mail->Body = '<h1>Hello, this is a test email!</h1>';

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