How can PHP-Mailer be used as an alternative to the mail() function for sending emails?

The PHP `mail()` function is often unreliable and lacks features for sending complex emails. PHP-Mailer is a popular library that provides a more robust and flexible solution for sending emails in PHP. By using PHP-Mailer, you can easily send emails with attachments, HTML content, and SMTP authentication, making it a great alternative to the `mail()` function.

// Include the PHP-Mailer library
require 'path/to/PHPMailer/PHPMailerAutoload.php';

// Create a new PHP-Mailer instance
$mail = new PHPMailer;

// Set up the email parameters
$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
$mail->Subject = 'Subject of the Email';
$mail->Body = 'Body of the Email';

// Send the email using SMTP
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your_smtp_username';
$mail->Password = 'your_smtp_password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;

// Add attachments if needed
$mail->addAttachment('/path/to/file.pdf');

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