How can PHP beginners troubleshoot errors like "SMTP ERROR: Failed to connect to server" when using PHPMailer?

The "SMTP ERROR: Failed to connect to server" error typically occurs when there is an issue with the SMTP server configuration or network connectivity. To troubleshoot this error, beginners can start by checking the SMTP server settings, ensuring that the server is reachable from the PHP script, and verifying the network connection.

// Include the PHPMailer library
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

// Instantiate the PHPMailer object
$mail = new PHPMailer(true);

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

// Set email content and recipient
$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
$mail->Subject = 'Test Email';
$mail->Body = 'This is a test email';

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