1

这是我发送电子邮件的 smtp 代码:

function smtp_mail($from, $to, $subject, $message, $headers="", $params=array()) {
$errno = "";
$errstr = "";
$smtpConnect = fsockopen("mail2.allramhosting.com", "25", $errno, $errstr, 20);


if (!empty($smtpConnect)) {

    if ($params['use_html']) {
        $extra_headers .= "MIME-Version: 1.0\nContent-Type: text/html; charset=\"utf-8\"\nContent-Transfer-Encoding: 7bit\n";
    }
    $headers = "To: " . $to . "\nFrom: " . $from . "\nSubject: " . $subject . "\nDate: " . date('r') . "\n" . $extra_headers . $headers;

    if (substr($headers, -1) == "\n") $headers = substr($headers, 0, -1); // The last character should not be newline


    fputs($smtpConnect, "HELO networkssms.com\r\n");
    fputs($smtpConnect, "MAIL FROM: " . $from . "\r\n");
    fputs($smtpConnect, "RCPT TO: " . $to . "\r\n");
    fputs($smtpConnect, "DATA\r\n");
    fputs($smtpConnect, $headers . "\r\n\r\n");
    fputs($smtpConnect, $message . "\r\n.\r\n"); // send message and finish
    fputs($smtpConnect,"QUIT" . $newLine);
    fclose($smtpConnect);
    return true;
}
return false;

}

这是smtp邮件功能的调用代码:

smtp_mail($from, $user_to ,$user_subject, $user_message,"MIME-Version: 1.0\nContent-Type: text/html; charset=\"utf-8\"\nContent-Transfer-Encoding: 7bit\n");

$from,$user_to ,$user_subject, $user_message有自己的价值观。

我想检查电子邮件是否已发送,如果未发送,我想再次发送。

我怎样才能做到这一点 ?

4

1 回答 1

1

首先,您应该检查连接是否正常:

$smtpConnect = fsockopen("mail2.allramhosting.com", "25", $errno, $errstr, 20);

fsockopenfalse如果连接失败则返回。所以添加下面提到的代码

if (!$smptConnect) {
   echo "ERROR: $errno - $errstr".PHP_EOL;
   return false;
} else {
   // send 
   return true;
}

您向 SMTP 服务器发出的每个命令都会给出一个数字响应 - 您应该在继续执行下一个命令之前检查响应是否正确 - 一旦您阅读了最后一条评论并且一切正常 - 这是确认电子邮件已发送..见这个链接解释了你应该从每个命令中得到什么响应

所以例如

fputs($smtpConnect, "HELO networkssms.com\r\n");

应该用代码250来检查你可以做的事情:

fputs($smtpConnect, "HELO networkssms.com\r\n");
$rcode = fgets($smtpConnect, 256);
if (substr($rcode, 0, 3)!= '250') {    // check the first 3 characters ie the response code
   echo "email sending failed" . PHP_EOL;
}

您需要为每个命令执行此操作 - 检查每个命令的响应代码是否符合预期。您可以创建一个简单的函数来检查每个响应

function check_response($smtpConnect,$expected_response) {
    $rcode = fgets($smtpConnect, 256);
    if (substr($rcode, 0, 3)!= $expected_response) {    // check the first 3 characters ie the response code
       echo "email sending failed" . PHP_EOL;
       return false;
    }
    return true;
}

然后你可以这样做:

fputs($smtpConnect, "HELO networkssms.com\r\n");
if (!check_reponse($smptConnect,'250')) {
   return false;
}

同样,您需要对发送的每个命令执行此操作。我相信你明白这个想法......

于 2012-04-12T08:59:08.553 回答