How can PHPMailer be used to send HTML emails effectively?
To send HTML emails effectively using PHPMailer, you need to set the Content-Type header to "text/html" and provide the HTML content in the body of the email. This will ensure that the email is displayed as HTML content when received by the recipient.
<?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('your@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
$mail->isHTML(true);
$mail->Subject = 'HTML Email Test';
$mail->Body = '<h1>Hello, this is a test HTML email!</h1>';
$mail->send();
echo 'Email sent successfully';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
?>
Related Questions
- What is the significance of the error message "Notice: Undefined index: short" in PHP code when accessing data from a database?
- How can PHP sessions be used to transfer user information between pages?
- Is it recommended to store image data in a BLOB field in a MySQL database, or are there better alternatives for handling image files in PHP?