如何通过PHP Socket SMTP握手验证邮箱有效性?代码误判问题
问题:PHP Socket SMTP验证邮箱有效性时误判真实邮箱为无效
我希望通过PHP Socket与SMTP服务器握手,验证收件人邮箱地址是否有效,但当前代码总是将真实存在的邮箱判定为无效。
以下是我用于验证的代码:
$smtpHost = 'mail.sender.com'; // Replace with your SMTP server hostname $smtpPort = 587; // Use the appropriate port for your SMTP server $localDomain = 'sender.com'; // Replace with the name of your server $recipientEmail = 'noreply@receiver.com'; // Replace with the recipient's email $username = 'noreply@sender.com'; $password = '**********'; list(,$domain) = explode("@",$recipientEmail); // Open a socket connection to the SMTP server $socket = fsockopen($smtpHost, $smtpPort, $errno, $errstr, 30); if (!$socket) { echo "Failed to open socket: $errstr ($errno)"; } else { function readResponse($socket) { $response = ''; do { $line = fgets($socket, 512); $response .= $line; } while (preg_match('/^\d{3}-/', $line)); echo $response; return $response; } // Read the initial response from the server $response = readResponse($socket); // Send the EHLO (or HELO) command to the SMTP server fputs($socket, "EHLO $localDomain\r\n"); // Use EHLO or HELO as needed $response = readResponse($socket); // Check if the server responds with a 250 code indicating a successful greeting if (preg_match('/^250/', $response)) { // Send the AUTH command with your SMTP credentials (username and password) $response = readResponse($socket); fputs($socket, "AUTH LOGIN\r\n"); $response = readResponse($socket); if (preg_match('/^334/', $response)) { // Send the base64-encoded username fputs($socket, base64_encode($username) . "\r\n"); $response = readResponse($socket); if (preg_match('/^334/', $response)) { // Send the base64-encoded password fputs($socket, base64_encode($password) . "\r\n"); $response = readResponse($socket); // Check if authentication was successful (usually 235 for success) if (preg_match('/^235/', $response)) { // Send the sender's email address fputs($socket, "MAIL FROM:<$username>\r\n"); $response = readResponse($socket); // Now you can send the RCPT TO command fputs($socket, "RCPT TO:<$recipientEmail>\r\n"); $response = readResponse($socket); // Send VRFY command fputs($socket, "VRFY $recipientEmail\r\n"); $response = readResponse($socket); // Check the response if (preg_match('/^250/', $response)) { echo "The email address '$recipientEmail' exists on the server.\r\n"; } else { echo "The email address '$recipientEmail' does not exist or the server doesn't support VRFY.\r\n"; } // Close the connection fputs($socket, "QUIT\r\n"); $response = readResponse($socket); } else { echo "SMTP authentication failed.\r\n"; } } else { echo "Failed to send the password.\r\n"; } } else { echo "Failed to send the username.\r\n"; } } else { echo "Failed to greet the SMTP server.\r\n"; } // Close the socket connection when done fclose($socket); }
代码运行后,响应提示“该邮箱不存在或服务器不支持VRFY”,但实际该邮箱是真实存在的,请求协助解决代码的误判问题。
内容的提问来源于stack exchange,提问作者Waseem Jutt
相关产品推荐
相关产品推荐

