<?php
function send_smtp_mail($conf, $to_email, $to_name, $subject, $html_body) {
    $smtp = $conf['smtp'];
    $host = $smtp['host'];
    $port = $smtp['port'] ?? 587;
    $username = $smtp['username'];
    $password = $smtp['password'];
    $secure = strtolower($smtp['secure'] ?? 'tls'); // tls or ssl
    $from_email = $conf['from']['email'];
    $from_name = $conf['from']['name'];
    $timeout = 30;
    $remote_socket = ($secure === 'ssl' ? 'ssl://' : '') . $host . ':' . $port;
    $fp = @stream_socket_client($remote_socket, $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT);
    if (!$fp) { error_log("SMTP connect failed: $errno $errstr"); return false; }
    stream_set_timeout($fp, $timeout);
    fgets($fp, 512);
    fwrite($fp, "EHLO localhost\r\n");
    fread($fp, 1024);
    if ($secure === 'tls') {
        fwrite($fp, "STARTTLS\r\n");
        fgets($fp, 512);
        if (!stream_socket_enable_crypto($fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) { error_log('Failed enabling TLS'); fclose($fp); return false; }
        fwrite($fp, "EHLO localhost\r\n");
        fread($fp, 1024);
    }
    fwrite($fp, "AUTH LOGIN\r\n");
    fgets($fp, 512);
    fwrite($fp, base64_encode($username) . "\r\n");
    fgets($fp, 512);
    fwrite($fp, base64_encode($password) . "\r\n");
    fgets($fp, 512);
    fwrite($fp, "MAIL FROM: <" . $from_email . ">\r\n");
    fgets($fp, 512);
    fwrite($fp, "RCPT TO: <" . $to_email . ">\r\n");
    fgets($fp, 512);
    fwrite($fp, "DATA\r\n");
    fgets($fp, 512);
    $headers = [];
    $headers[] = 'From: ' . $from_name . ' <' . $from_email . '>';
    $headers[] = 'To: ' . $to_name . ' <' . $to_email . '>';
    $headers[] = 'Subject: ' . $subject;
    $headers[] = 'MIME-Version: 1.0';
    $headers[] = 'Content-Type: text/html; charset=UTF-8';
    $headers[] = 'Content-Transfer-Encoding: 7bit';
    $message = implode("\r\n", $headers) . "\r\n\r\n" . $html_body . "\r\n\r\n.";
    fwrite($fp, $message . "\r\n");
    fgets($fp, 512);
    fwrite($fp, "QUIT\r\n");
    fgets($fp, 512);
    fclose($fp);
    return true;
}
?>