How can one troubleshoot and resolve SMTP connection issues in PHPMailer?

To troubleshoot and resolve SMTP connection issues in PHPMailer, you can start by checking the SMTP server settings, ensuring that the correct host, port, username, and password are being used. Additionally, make sure that the firewall or antivirus software is not blocking the SMTP connection. You can also enable debugging in PHPMailer to get more information about the connection issue.

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->Port = 587;
    $mail->SMTPAuth = true;
    $mail->Username = 'your_username';
    $mail->Password = 'your_password';
    
    // Enable verbose debugging
    $mail->SMTPDebug = 2;

    $mail->setFrom('from@example.com', 'Your Name');
    $mail->addAddress('recipient@example.com', 'Recipient Name');
    
    $mail->Subject = 'Testing SMTP connection';
    $mail->Body = 'This is a test email';

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