How can PHP developers troubleshoot SMTP connection issues when sending emails?

To troubleshoot SMTP connection issues when sending emails in PHP, developers can check the SMTP server settings, ensure the correct port is being used, verify the credentials are correct, and check for any firewall restrictions. Additionally, developers can enable error reporting to get more detailed information about any connection errors.

// Example PHP code snippet to troubleshoot SMTP connection issues

// Set SMTP server settings
$smtpServer = 'smtp.example.com';
$smtpPort = 587;
$username = 'your_username';
$password = 'your_password';

// Create a new PHPMailer instance
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);

try {
    // Server settings
    $mail->isSMTP();
    $mail->Host = $smtpServer;
    $mail->SMTPAuth = true;
    $mail->Username = $username;
    $mail->Password = $password;
    $mail->SMTPSecure = 'tls';
    $mail->Port = $smtpPort;

    // Enable verbose error reporting
    $mail->SMTPDebug = 2;

    // Send email
    $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 'Email could not be sent. Error: ' . $mail->ErrorInfo;
}