How can PHPMailer be used as an alternative to the mail() function in PHP for sending emails with HTML content?
The mail() function in PHP is limited in its ability to send HTML content in emails. PHPMailer is a popular library that provides a more robust and flexible solution for sending emails with HTML content. By using PHPMailer, you can easily create and send HTML emails with attachments, inline images, and more.
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
$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');
$mail->isHTML(true);
$mail->Subject = 'Subject of the Email';
$mail->Body = '<h1>This is an HTML email</h1><p>With some <strong>bold</strong> and <em>italic</em> text.</p>';
$mail->send();
echo 'Email sent successfully';
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo;
}
?>