In cases where PHPmailer fails to send emails, what steps can be taken to diagnose and resolve the issue, especially when error messages indicate recipient email failures?

When PHPmailer fails to send emails and error messages indicate recipient email failures, the first step is to check if the recipient email address is valid and correctly formatted. Additionally, ensure that the SMTP settings are correctly configured and that the email server is not blocking the outgoing emails. You can also try sending the email to a different email address to see if the issue persists.

// Example code to diagnose and resolve PHPmailer email sending issue
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$mail = new PHPMailer(true);

try {
    // Server settings
    $mail->isSMTP();
    $mail->Host = 'smtp.example.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'your@example.com';
    $mail->Password = 'your_password';
    $mail->SMTPSecure = 'tls';
    $mail->Port = 587;

    // Recipient
    $mail->setFrom('your@example.com', 'Your Name');
    $mail->addAddress('recipient@example.com', 'Recipient Name');

    // Content
    $mail->isHTML(true);
    $mail->Subject = 'Subject';
    $mail->Body = 'Message body';

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