<?php
// SMTP configuration
$smtpHost = "smtp.gmail.com";
$smtpPort = 587;
$smtpUser = "technicianjakir@gmail.com"; // Your Gmail address
$smtpPass = "tkqilwpkwhihtojg"; // Your App Password (not Gmail password)

// Email information
$fromEmail = "technicianjakir@gmail.com";
$fromName = "MailTest"; // Change this to your desired name
$toEmail = "jakirits09@gmail.com"; // Recipient email
$subject = "Test Email using Raw PHP";
$message = "This is a test email sent using raw PHP and Gmail SMTP.";

// Headers
$headers = "From: $fromName <$fromEmail>\r\n";
$headers .= "Reply-To: $fromEmail\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\r\n";

// SMTP connection
$socket = fsockopen($smtpHost, $smtpPort, $errno, $errstr, 10);

if (!$socket) {
    echo "<script>alert('Failed to connect to the SMTP server: $errstr ($errno)');</script>";
    exit;
}

// Function to send a command to the SMTP server and check the response
function sendCommand($socket, $command, $expectedResponse) {
    fwrite($socket, $command . "\r\n");
    $response = fgets($socket, 512);
    if (substr($response, 0, 3) != $expectedResponse) {
        return false; // If the response does not match the expected response, return false
    }
    return true;
}

// Try to send the email and check responses
try {
    if (!sendCommand($socket, "EHLO $smtpHost", "250")) throw new Exception("EHLO failed");
    if (!sendCommand($socket, "STARTTLS", "220")) throw new Exception("STARTTLS failed");
    stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
    if (!sendCommand($socket, "EHLO $smtpHost", "250")) throw new Exception("EHLO after STARTTLS failed");
    if (!sendCommand($socket, "AUTH LOGIN", "334")) throw new Exception("AUTH LOGIN failed");
    if (!sendCommand($socket, base64_encode($smtpUser), "334")) throw new Exception("Username rejected");
    if (!sendCommand($socket, base64_encode($smtpPass), "235")) throw new Exception("Password rejected");
    if (!sendCommand($socket, "MAIL FROM: <$fromEmail>", "250")) throw new Exception("MAIL FROM failed");
    if (!sendCommand($socket, "RCPT TO: <$toEmail>", "250")) throw new Exception("RCPT TO failed");
    if (!sendCommand($socket, "DATA", "354")) throw new Exception("DATA command failed");
    if (!sendCommand($socket, "Subject: $subject\r\n$headers\r\n\r\n$message\r\n.", "250")) throw new Exception("Message body failed");
    if (!sendCommand($socket, "QUIT", "221")) throw new Exception("QUIT failed");

    fclose($socket);
    echo "<script>alert('Email sent successfully!');</script>";
} catch (Exception $e) {
    fclose($socket);
    echo "<script>alert('Email sending failed: " . $e->getMessage() . "');</script>";
}
?>
