這裡示範如何使用 SMTP 發送電子郵件。這包括在發送電子郵件過程中對伺服器響應進行初步檢查。可以通過更全面的處理結果代碼來改進...或者在連接到第一個郵件交換器失敗後,繼續連接下一個郵件交換器。
<?php
function another_mail($to,$subject,$headers,$message)
{
$from="me@example.com";
list($me,$mydomain) = split("@",$from);
list($user,$domain) = split("@",$to,2);
if(getmxrr($domain,$mx,$weight) == 0) return FALSE;
array_multisort($mx,$weight);
$success=0;
foreach($mx as $host) {
$connection = fsockopen ($host, 25, $errno, $errstr, 1);
if (!$connection)
continue;
$res=fgets($connection,256);
if(substr($res,0,3) != "220") break;
fputs($connection, "HELO $mydomain\n");
$res=fgets($connection,256);
if(substr($res,0,3) != "250") break;
fputs($connection, "MAIL FROM: $from\n");
$res=fgets($connection,256);
if(substr($res,0,3) != "250") break;
fputs($connection, "RCPT TO: $to\n");
$res=fgets($connection,256);
if(substr($res,0,3) != "250") break;
fputs($connection, "DATA\n");
$res=fgets($connection,256);
if(substr($res,0,3) != "354") break;
fputs($connection, "To: $to\nFrom: $from\nSubject: $subject\n$headers\n\n$message\n.\n");
$res=fgets($connection,256);
if(substr($res,0,3) != "250") break;
fputs($connection,"QUIT\n");
$res=fgets($connection,256);
if(substr($res,0,3) != "221") break;
$success=1;
break;
}
if($connection) {
if($success==0) fputs($connection, "QUIT\n");
fclose ($connection);
}
return $success?TRUE:FALSE;
}
another_mail("recipient@example.com","My Subject","X-mailer: PHP Script\nX-another-header: Whatever","Test email body.\n\nNote if you actually put a period on a line\nby itself, the function will terminate prematurely.\n\nYou will get a partial email sent though.\n");
?>