How can PHPMailer be used as an alternative to the mail() function for sending emails with attachments and HTML content?

The mail() function in PHP is limited in its ability to send emails with attachments and HTML content. PHPMailer is a popular alternative that provides more functionality and flexibility for sending emails with attachments and HTML content.

// Include the PHPMailer library
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';
require 'path/to/PHPMailer/src/Exception.php';

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

// Set 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('your@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
$mail->Subject = 'Subject of the email';
$mail->isHTML(true);
$mail->Body = '<p>This is the HTML content of the email.</p>';

// Attach a file to the email
$mail->addAttachment('path/to/file.pdf');

// Send the email
if($mail->send()) {
    echo 'Email sent successfully';
} else {
    echo 'Email could not be sent';
}