Being on a shared hosted server, I cannot install anything but I’m looking for an alternative to the insecure mail() function that is built-in to PHP. I do have SMTP server access and found and slightly modified some code written by others but not sure what to do with it. While I can see what it does in general, how does it actually send a message through fwrite() alone or does it simply generate better, more secure headers?
Also, any idea what $B = 8192; is for?
(Message() is my own custom function that simply presents a message on-screen and has nothing to do with the functionality.)
// FOR TESTING PURPOSES ONLY
function smtpmail($to, $subject, $body, $headers) {
$smtp = stream_socket_client('tcp://mail.someserver.com:25', $eno, $estr, 30);
if (!$smtp) :
Message("$estr ($eno)<br />\n");
endif;
$B = 8192;
$c = "\r\n";
$s = '[email protected]';
fwrite($smtp, 'helo ' . $_ENV['HOSTNAME'] . $c);
$junk = fgets($smtp, $B);
// ENVELOPE
fwrite($smtp, 'mail from: ' . $s . $c);
$junk = fgets($smtp, $B);
fwrite($smtp, 'rcpt to: ' . $to . $c);
$junk = fgets($smtp, $B);
fwrite($smtp, 'data' . $c);
$junk = fgets($smtp, $B);
// HEADER
fwrite($smtp, 'To: ' . $to . $c);
if(strlen($subject)) fwrite($smtp, 'Subject: ' . $subject . $c);
if(strlen($headers)) fwrite($smtp, $headers); // Must be \r\n (delimited)
fwrite($smtp, $headers . $c);
// BODY
if(strlen($body)) fwrite($smtp, $body . $c);
fwrite($smtp, $c . '.' . $c);
$junk = fgets($smtp, $B);
// CLOSE
fwrite($smtp, 'quit' . $c);
$junk = fgets($smtp, $B);
fclose($smtp);
}