Trouble Sending Emails with PHP Using PHPMailer: Getting ‘Cannot Send Mail’ Error

I’m encountering an issue while trying to send emails using PHP’s PHPMailer library. I’m getting an error that says ‘Cannot Send Mail.’ and I’ve tried different ways to send mail even I got helped from ChatGpt but I could not. I’ve followed the documentation and my code looks like this:

<form action="mail.php" method="post">
    <input type="text" name="name">
    <input type="email" name="email" id="">
    <input type="submit" value="submit">
</form>

<?php
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;

require __DIR__ . '/PHPMailer-master/PHPMailer.php';
require __DIR__ . '/PHPMailer-master/Exception.php';
require __DIR__ . '/PHPMailer-master/SMTP.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST['name'];
    $email = $_POST['email'];

    $mail = new PHPMailer(true);

    try {
        // SMTP configuration
        $mail->isSMTP();
        $mail->Host = 'smtp.gmail.com';
        $mail->SMTPAuth = true;
        $mail->Username = '[email protected]';
        $mail->Password = 'mypassword'; // Replace with your Gmail password
        $mail->SMTPSecure = 'tls';
        $mail->Port = 587;

        // Sender and recipient details
        $mail->setFrom('[email protected]', 'Ahmed Maajid');
        $mail->addAddress('[email protected]'); // Set your Gmail address as both sender and recipient

        // Email content
        $mail->isHTML(false);
        $mail->Subject = 'New submission from your website';
        $mail->Body = 'Name: ' . $name . "nn" . 'Email: ' . $email;

        $mail->send();
        echo 'Email sent successfully!';
    } catch (Exception $e) {
        echo 'Oops! There was a problem: ' . $mail->ErrorInfo;
    }
}
?>