#!/usr/bin/env python3
"""
Тихая проверка одной SMTP креденшелы - только логин, без отправки писем
"""
import socket
import base64
import ssl

def test_smtp_login_quiet(host, port, username, password):
    """Тихая проверка SMTP login без отправки писем"""
    try:
        # Создаем SSL контекст
        context = ssl.create_default_context()
        
        # Подключаемся к SMTP серверу
        with socket.create_connection((host, port), timeout=10) as sock:
            # Получаем приветствие
            response = sock.recv(1024).decode('utf-8', errors='ignore')
            if not response.startswith('220'):
                return False, f"SMTP server not ready: {response[:50]}"
            
            # Отправляем EHLO
            sock.send(b'EHLO test.com\r\n')
            response = sock.recv(1024).decode('utf-8', errors='ignore')
            if not response.startswith('250'):
                return False, f"EHLO failed: {response[:50]}"
            
            # Проверяем поддержку AUTH LOGIN
            if 'AUTH' not in response.upper():
                return False, "Server doesn't support authentication"
            
            # Отправляем AUTH LOGIN
            sock.send(b'AUTH LOGIN\r\n')
            response = sock.recv(1024).decode('utf-8', errors='ignore')
            if not response.startswith('334'):
                return False, f"AUTH LOGIN rejected: {response[:50]}"
            
            # Отправляем username (base64)
            username_b64 = base64.b64encode(username.encode()).decode()
            sock.send(f'{username_b64}\r\n'.encode())
            response = sock.recv(1024).decode('utf-8', errors='ignore')
            if not response.startswith('334'):
                return False, f"Username rejected: {response[:50]}"
            
            # Отправляем password (base64)
            password_b64 = base64.b64encode(password.encode()).decode()
            sock.send(f'{password_b64}\r\n'.encode())
            response = sock.recv(1024).decode('utf-8', errors='ignore')
            
            # Проверяем результат аутентификации
            if response.startswith('235'):
                return True, "Authentication successful"
            else:
                return False, f"Authentication failed: {response[:50]}"
                
    except socket.timeout:
        return False, "Connection timeout"
    except ConnectionRefusedError:
        return False, "Connection refused"
    except Exception as e:
        return False, f"Error: {str(e)}"

def main():
    print("=== Тихая проверка SMTP credentials ===\n")
    
    # Используем первую креденшелу из списка
    cred = {
        'db': '2210CHILDERSOILUAP01',
        'username': 'testing@irely.com',
        'password': 'YY=G)o+ueMDGw#H',
        'host': 'smtp.office365.com',
        'port': 587
    }
    
    print(f"Testing: {cred['username']}@{cred['host']}:{cred['port']}")
    print(f"Database: {cred['db']}")
    
    success, message = test_smtp_login_quiet(
        cred['host'], 
        cred['port'], 
        cred['username'], 
        cred['password']
    )
    
    if success:
        print(f"  ✅ {message}")
    else:
        print(f"  ❌ {message}")
    
    print("\n=== Результат ===")
    if success:
        print("✅ SMTP login successful - credentials are valid")
    else:
        print("❌ SMTP login failed - credentials are invalid")

if __name__ == '__main__':
    main()
