How can HTML formatting be properly implemented in PHP emails using the PHPMailer class?
When sending HTML-formatted emails using the PHPMailer class in PHP, you need to set the Content-Type header to 'text/html'. This tells the email client that the message content is in HTML format. You can achieve this by using the PHPMailer class method `isHTML(true)`.
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
//Server settings
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@example.com';
$mail->Password = 'yourpassword';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
//Recipients
$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'HTML Email Test';
$mail->Body = '<h1>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}";
}
Keywords
Related Questions
- How can PHP be used to send HTML emails with correct formatting and display in mail clients?
- How can the misuse of escape functions like mysql_real_escape_string() lead to vulnerabilities in PHP applications?
- How can the removal of a post after a solution is found impact the overall forum discussion and knowledge sharing?