khalequzzaman17

Check SMTP Connection in PHP

Jun 18th, 2023 (edited)
366
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.06 KB | None | 0 0
  1. <?php
  2. function checkSMTPConnection($email, $password, $host, $port, $secured)
  3. {
  4.     // Establish a TCP/IP socket connection
  5.     $context = stream_context_create([
  6.         'ssl' => [
  7.             'verify_peer' => false,
  8.             'verify_peer_name' => false,
  9.         ],
  10.     ]);
  11.    
  12.     $socket = stream_socket_client("tcp://$host:$port", $errno, $errstr, 10, STREAM_CLIENT_CONNECT, $context);
  13.  
  14.     if ($socket) {
  15.         // Read the server's response
  16.         $response = fread($socket, 8192);
  17.        
  18.         // Send EHLO/HELO command
  19.         fwrite($socket, "EHLO example.com\r\n");
  20.         $response = fread($socket, 8192);
  21.        
  22.         // Send STARTTLS command if using secured connection
  23.         if ($secured) {
  24.             fwrite($socket, "STARTTLS\r\n");
  25.             $response = fread($socket, 8192);
  26.         }
  27.        
  28.         // Authenticate with the server
  29.         fwrite($socket, "AUTH LOGIN\r\n");
  30.         $response = fread($socket, 8192);
  31.  
  32.         // Send base64-encoded email and password
  33.         fwrite($socket, base64_encode($email) . "\r\n");
  34.         $response = fread($socket, 8192);
  35.  
  36.         fwrite($socket, base64_encode($password) . "\r\n");
  37.         $response = fread($socket, 8192);
  38.        
  39.         // Check if authentication is successful
  40.         if (strpos($response, '235') !== false) {
  41.             // SMTP connection successful
  42.             fwrite($socket, "QUIT\r\n");
  43.             fclose($socket);
  44.             return true;
  45.         } else {
  46.             // Authentication failed
  47.             fclose($socket);
  48.             return false;
  49.         }
  50.     } else {
  51.         // SMTP connection failed
  52.         return false;
  53.     }
  54. }
  55.  
  56. // Usage example
  57. $email = 'your-email@example.com';
  58. $password = 'your-password';
  59. $host = 'smtp.example.com';
  60. $port = 587; // Change this to the appropriate SMTP port
  61. $secured = true; // Set to true for secured connection (TLS/SSL)
  62.  
  63. if (checkSMTPConnection($email, $password, $host, $port, $secured)) {
  64.     echo "SMTP connection successful!";
  65. } else {
  66.     echo "SMTP connection failed!";
  67. }
  68.  
Add Comment
Please, Sign In to add comment