What are common causes for PHPMailer SMTP connection failures?

Common causes for PHPMailer SMTP connection failures include incorrect SMTP server settings, firewall restrictions blocking outgoing connections, and SSL/TLS configuration issues. To solve this issue, double-check the SMTP server settings, ensure that the firewall allows outgoing connections on the SMTP port, and verify the SSL/TLS configuration.

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$mail = new PHPMailer();

// Set SMTP server settings
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->Username = 'your_username';
$mail->Password = 'your_password';
$mail->SMTPSecure = 'tls';

// Enable debugging
$mail->SMTPDebug = 2;

// Send email
if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}