How can the PHPMailer library be used to avoid email header issues in PHP applications?

Email header issues in PHP applications can be avoided by using the PHPMailer library, which provides a secure and reliable way to send emails without worrying about header injection vulnerabilities. PHPMailer automatically sanitizes email headers, preventing malicious code injections. By using PHPMailer, developers can ensure that their email communications are safe and secure.

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);

try {
    $mail->setFrom('from@example.com', 'Your Name');
    $mail->addAddress('recipient@example.com', 'Recipient Name');
    $mail->Subject = 'Subject';
    $mail->Body = 'Message body';

    $mail->isSMTP();
    $mail->Host = 'smtp.example.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'username';
    $mail->Password = 'password';
    $mail->SMTPSecure = 'tls';
    $mail->Port = 587;

    $mail->send();
    echo 'Email sent successfully';
} catch (Exception $e) {
    echo 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo;
}
?>