How can one troubleshoot SMTP connection issues in PHP mail sending?

To troubleshoot SMTP connection issues in PHP mail sending, you can check the SMTP server settings, ensure the correct port is being used, verify the credentials are correct, and check for any firewall or network issues blocking the connection.

<?php
$to = "recipient@example.com";
$subject = "Test Email";
$message = "This is a test email.";

$smtpServer = 'smtp.example.com';
$smtpUsername = 'your_smtp_username';
$smtpPassword = 'your_smtp_password';
$smtpPort = 587;

// Create a new PHPMailer instance
$mail = new PHPMailer(true);

// Set SMTP settings
$mail->IsSMTP();
$mail->Host = $smtpServer;
$mail->SMTPAuth = true;
$mail->Username = $smtpUsername;
$mail->Password = $smtpPassword;
$mail->SMTPSecure = 'tls';
$mail->Port = $smtpPort;

// Send the email
$mail->SetFrom($smtpUsername);
$mail->AddAddress($to);
$mail->Subject = $subject;
$mail->Body = $message;

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