false, 'error' => "Connection failed: $errstr ($errno)"]; } $resp = fgets($socket, 512); if (substr($resp, 0, 3) !== '220') { fclose($socket); return ['ok' => false, 'error' => "Server greeting failed: $resp"]; } // EHLO fwrite($socket, "EHLO konesaliturku.fi\r\n"); $resp = ''; while ($line = fgets($socket, 512)) { $resp .= $line; if ($line[3] === ' ') break; } // STARTTLS fwrite($socket, "STARTTLS\r\n"); $resp = fgets($socket, 512); if (substr($resp, 0, 3) !== '220') { fclose($socket); return ['ok' => false, 'error' => "STARTTLS failed: $resp"]; } // Enable TLS $crypto = stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT | STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT); if (!$crypto) { fclose($socket); return ['ok' => false, 'error' => "TLS handshake failed"]; } // EHLO again after TLS fwrite($socket, "EHLO konesaliturku.fi\r\n"); $resp = ''; while ($line = fgets($socket, 512)) { $resp .= $line; if ($line[3] === ' ') break; } // AUTH LOGIN fwrite($socket, "AUTH LOGIN\r\n"); $resp = fgets($socket, 512); if (substr($resp, 0, 3) !== '334') { fclose($socket); return ['ok' => false, 'error' => "AUTH failed: $resp"]; } fwrite($socket, base64_encode($user) . "\r\n"); $resp = fgets($socket, 512); if (substr($resp, 0, 3) !== '334') { fclose($socket); return ['ok' => false, 'error' => "AUTH user failed: $resp"]; } fwrite($socket, base64_encode($pass) . "\r\n"); $resp = fgets($socket, 512); if (substr($resp, 0, 3) !== '235') { fclose($socket); return ['ok' => false, 'error' => "AUTH password failed: $resp"]; } // MAIL FROM fwrite($socket, "MAIL FROM:<$from>\r\n"); $resp = fgets($socket, 512); if (substr($resp, 0, 3) !== '250') { fclose($socket); return ['ok' => false, 'error' => "MAIL FROM failed: $resp"]; } // RCPT TO fwrite($socket, "RCPT TO:<$to>\r\n"); $resp = fgets($socket, 512); if (substr($resp, 0, 3) !== '250') { fclose($socket); return ['ok' => false, 'error' => "RCPT TO failed: $resp"]; } // DATA fwrite($socket, "DATA\r\n"); $resp = fgets($socket, 512); if (substr($resp, 0, 3) !== '354') { fclose($socket); return ['ok' => false, 'error' => "DATA failed: $resp"]; } // Build message $fromHeader = $fromName ? "\"$fromName\" <$from>" : $from; $msg = "From: $fromHeader\r\n"; $msg .= "To: $to\r\n"; $msg .= "Subject: =?UTF-8?B?" . base64_encode($subject) . "?=\r\n"; if ($replyTo) { $msg .= "Reply-To: $replyTo\r\n"; } $msg .= "MIME-Version: 1.0\r\n"; $msg .= "Content-Type: text/plain; charset=UTF-8\r\n"; $msg .= "Content-Transfer-Encoding: 8bit\r\n"; $msg .= "Date: " . date('r') . "\r\n"; $msg .= "\r\n"; $msg .= $body; $msg .= "\r\n.\r\n"; fwrite($socket, $msg); $resp = fgets($socket, 512); // QUIT fwrite($socket, "QUIT\r\n"); fclose($socket); if (substr($resp, 0, 3) === '250') { return ['ok' => true]; } return ['ok' => false, 'error' => "Send failed: $resp"]; }