51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

smtp.class.php 发信类+最新可用+支持 PHP7

发信配置

<?php
`/**
 * 已兼容php7
 * 注:本邮件类都是经过我测试成功了的,如果大家发送邮件的时候遇到了失败的问题,请从以下几点排查:
 * 1. 用户名和密码是否正确;
 * 2. 检查邮箱设置是否启用了smtp服务;
 * 3. 是否是php环境的问题导致;
 * 4. 将26行的$smtp-&gt;debug = false改为true,可以显示错误信息,然后可以复制报错信息到网上搜一下错误的原因;
 * 5. 如果还是不能解决,可以访问:http://www.daixiaorui.com/read/16.html#viewpl 
 *    下面的评论中,可能有你要找的答案。
 *
 *
 * Last update time:2017/06
 * UPDATE:
 * 1、替换了高版本不支持的写法,如ereg、ereg_replace.
 * 2、将 var 改为 public/private等.
 * 3、使其兼容php7.
 * 
 */

require_once "Smtp.class.php";
//******************** 配置信息 ********************************
$smtpserver = "smtp.daixiaorui.com";//SMTP服务器
$smtpserverport =25;//SMTP服务器端口
$smtpusermail = "web@daixiaorui.com";//SMTP服务器的用户邮箱
$smtpemailto = $_POST['toemail'];//发送给谁
$smtpuser = "web@daixiaorui.com";//SMTP服务器的用户帐号,注:部分邮箱只需@前面的用户名
$smtppass = "您的邮箱密码";//SMTP服务器的用户密码
$mailtitle = $_POST['title'];//邮件主题
$mailcontent = "&lt;h1&gt;".$_POST['content']."&lt;/h1&gt;";//邮件内容
$mailtype = "HTML";//邮件格式(HTML/TXT),TXT为文本邮件
//************************ 配置信息 ****************************
$smtp = new Smtp($smtpserver,$smtpserverport,true,$smtpuser,$smtppass);//这里面的一个true是表示使用身份验证,否则不使用身份验证.
$smtp-&gt;debug = false;//是否显示发送的调试信息
$state = $smtp-&gt;sendmail($smtpemailto, $smtpusermail, $mailtitle, $mailcontent, $mailtype);

echo "&lt;div style='width:300px; margin:36px auto;'&gt;";
if($state==""){
	echo "对不起,邮件发送失败!请检查邮箱填写是否有误。";
	echo "&lt;a href='index.html'&gt;点此返回&lt;/a&gt;";
	exit();
}
echo "恭喜!邮件发送成功!!";
echo "&lt;a href='index.html'&gt;点此返回&lt;/a&gt;";
echo "&lt;/div&gt;";
`
?>

如果是使用的 ssl 如 QQ 邮箱 ssl , 修改如下
$smtpserver = "ssl://smtp.qq.com";//SMTP服务器
$smtpserverport = 465;//SMTP服务器端口

stmp.class.php

<?php
class smtp
{
/* Public Variables */
public $smtp_port;
public $time_out;
public $host_name;
public $log_file;
public $relay_host;
public $debug;
public $auth;
public $user;
public $pass;
`/* Private Variables */
private $sock;

/* Constractor */
function smtp($relay_host = "", $smtp_port = 25, $auth = false, $user, $pass)
{
    $this-&gt;debug = FALSE;
    $this-&gt;smtp_port = $smtp_port;
    $this-&gt;relay_host = $relay_host;
    $this-&gt;time_out = 30; //is used in fsockopen() 
    # 
    $this-&gt;auth = $auth;//auth 
    $this-&gt;user = $user;
    $this-&gt;pass = $pass;
    # 
    $this-&gt;host_name = "localhost"; //is used in HELO command 
    $this-&gt;log_file = "";

    $this-&gt;sock = FALSE;
}

/* Main Function */
function sendmail($to, $from, $subject = "", $body = "", $mailtype, $cc = "", $bcc = "", $additional_headers = "")
{
    $mail_from = $this-&gt;get_address($this-&gt;strip_comment($from));
    $body = preg_replace("/(^|(\r\n))(\\.)/", "\\1.\\3", $body);
    $header = "MIME-Version:1.0\r\n";
    if ($mailtype == "HTML") {
        $header .= "Content-Type:text/html\r\n";
    }
    $header .= "To: " . $to . "\r\n";
    if ($cc != "") {
        $header .= "Cc: " . $cc . "\r\n";
    }
    $header .= "From: $from&lt;" . $from . "&gt;\r\n";
    $header .= "Subject: " . $subject . "\r\n";
    $header .= $additional_headers;
    $header .= "Date: " . date("r") . "\r\n";
    $header .= "X-Mailer:By Redhat (PHP/" . phpversion() . ")\r\n";
    list($msec, $sec) = explode(" ", microtime());
    $header .= "Message-ID: &lt;" . date("YmdHis", $sec) . "." . ($msec * 1000000) . "." . $mail_from . "&gt;\r\n";
    $TO = explode(",", $this-&gt;strip_comment($to));

    if ($cc != "") {
        $TO = array_merge($TO, explode(",", $this-&gt;strip_comment($cc)));
    }

    if ($bcc != "") {
        $TO = array_merge($TO, explode(",", $this-&gt;strip_comment($bcc)));
    }

    $sent = TRUE;
    foreach ($TO as $rcpt_to) {
        $rcpt_to = $this-&gt;get_address($rcpt_to);
        if (!$this-&gt;smtp_sockopen($rcpt_to)) {
            $this-&gt;log_write("Error: Cannot send email to " . $rcpt_to . "\n");
            $sent = FALSE;
            continue;
        }
        if ($this-&gt;smtp_send($this-&gt;host_name, $mail_from, $rcpt_to, $header, $body)) {
            $this-&gt;log_write("E-mail has been sent to &lt;" . $rcpt_to . "&gt;\n");
        } else {
            $this-&gt;log_write("Error: Cannot send email to &lt;" . $rcpt_to . "&gt;\n");
            $sent = FALSE;
        }
        fclose($this-&gt;sock);
        $this-&gt;log_write("Disconnected from remote host\n");
    }
    echo "&lt;br&gt;";
    echo $header;
    return $sent;
}

/* Private Functions */

function smtp_send($helo, $from, $to, $header, $body = "")
{
    if (!$this-&gt;smtp_putcmd("HELO", $helo)) {
        return $this-&gt;smtp_error("sending HELO command");
    }
    #auth 
    if ($this-&gt;auth) {
        if (!$this-&gt;smtp_putcmd("AUTH LOGIN", base64_encode($this-&gt;user))) {
            return $this-&gt;smtp_error("sending HELO command");
        }
        if (!$this-&gt;smtp_putcmd("", base64_encode($this-&gt;pass))) {
            return $this-&gt;smtp_error("sending HELO command");
        }
    }
    # 
    if (!$this-&gt;smtp_putcmd("MAIL", "FROM:&lt;" . $from . "&gt;")) {
        return $this-&gt;smtp_error("sending MAIL FROM command");
    }

    if (!$this-&gt;smtp_putcmd("RCPT", "TO:&lt;" . $to . "&gt;")) {
        return $this-&gt;smtp_error("sending RCPT TO command");
    }

    if (!$this-&gt;smtp_putcmd("DATA")) {
        return $this-&gt;smtp_error("sending DATA command");
    }

    if (!$this-&gt;smtp_message($header, $body)) {
        return $this-&gt;smtp_error("sending message");
    }

    if (!$this-&gt;smtp_eom()) {
        return $this-&gt;smtp_error("sending &lt;CR&gt;&lt;LF&gt;.&lt;CR&gt;&lt;LF&gt; [EOM]");
    }

    if (!$this-&gt;smtp_putcmd("QUIT")) {
        return $this-&gt;smtp_error("sending QUIT command");
    }

    return TRUE;
}

function smtp_sockopen($address)
{
    if ($this-&gt;relay_host == "") {
        return $this-&gt;smtp_sockopen_mx($address);
    } else {
        return $this-&gt;smtp_sockopen_relay();
    }
}

function smtp_sockopen_relay()
{
    $this-&gt;log_write("Trying to " . $this-&gt;relay_host . ":" . $this-&gt;smtp_port . "\n");
    $this-&gt;sock = @fsockopen($this-&gt;relay_host, $this-&gt;smtp_port, $errno, $errstr, $this-&gt;time_out);
    if (!($this-&gt;sock &amp;&amp; $this-&gt;smtp_ok())) {
        $this-&gt;log_write("Error: Cannot connenct to relay host " . $this-&gt;relay_host . "\n");
        $this-&gt;log_write("Error: " . $errstr . " (" . $errno . ")\n");
        return FALSE;
    }
    $this-&gt;log_write("Connected to relay host " . $this-&gt;relay_host . "\n");
    return TRUE;
}

function smtp_sockopen_mx($address)
{
    $domain = preg_replace("/^.+@([^@]+)$/", "\\1", $address);
    if (!@getmxrr($domain, $MXHOSTS)) {
        $this-&gt;log_write("Error: Cannot resolve MX \"" . $domain . "\"\n");
        return FALSE;
    }
    foreach ($MXHOSTS as $host) {
        $this-&gt;log_write("Trying to " . $host . ":" . $this-&gt;smtp_port . "\n");
        $this-&gt;sock = @fsockopen($host, $this-&gt;smtp_port, $errno, $errstr, $this-&gt;time_out);
        if (!($this-&gt;sock &amp;&amp; $this-&gt;smtp_ok())) {
            $this-&gt;log_write("Warning: Cannot connect to mx host " . $host . "\n");
            $this-&gt;log_write("Error: " . $errstr . " (" . $errno . ")\n");
            continue;
        }
        $this-&gt;log_write("Connected to mx host " . $host . "\n");
        return TRUE;
    }
    $this-&gt;log_write("Error: Cannot connect to any mx hosts (" . implode(", ", $MXHOSTS) . ")\n");
    return FALSE;
}

function smtp_message($header, $body)
{
    fputs($this-&gt;sock, $header . "\r\n" . $body);
    $this-&gt;smtp_debug("&gt; " . str_replace("\r\n", "\n" . "&gt; ", $header . "\n&gt; " . $body . "\n&gt; "));

    return TRUE;
}

function smtp_eom()
{
    fputs($this-&gt;sock, "\r\n.\r\n");
    $this-&gt;smtp_debug(". [EOM]\n");

    return $this-&gt;smtp_ok();
}

function smtp_ok()
{
    $response = str_replace("\r\n", "", fgets($this-&gt;sock, 512));
    $this-&gt;smtp_debug($response . "\n");

    if (!preg_match("/^[23]/", $response)) {
        fputs($this-&gt;sock, "QUIT\r\n");
        fgets($this-&gt;sock, 512);
        $this-&gt;log_write("Error: Remote host returned \"" . $response . "\"\n");
        return FALSE;
    }
    return TRUE;
}

function smtp_putcmd($cmd, $arg = "")
{
    if ($arg != "") {
        if ($cmd == "") $cmd = $arg;
        else $cmd = $cmd . " " . $arg;
    }

    fputs($this-&gt;sock, $cmd . "\r\n");
    $this-&gt;smtp_debug("&gt; " . $cmd . "\n");

    return $this-&gt;smtp_ok();
}

function smtp_error($string)
{
    $this-&gt;log_write("Error: Error occurred while " . $string . ".\n");
    return FALSE;
}

function log_write($message)
{
    $this-&gt;smtp_debug($message);

    if ($this-&gt;log_file == "") {
        return TRUE;
    }

    $message = date("M d H:i:s ") . get_current_user() . "[" . getmypid() . "]: " . $message;
    if (!@file_exists($this-&gt;log_file) || !($fp = @fopen($this-&gt;log_file, "a"))) {
        $this-&gt;smtp_debug("Warning: Cannot open log file \"" . $this-&gt;log_file . "\"\n");
        return FALSE;
    }
    flock($fp, LOCK_EX);
    fputs($fp, $message);
    fclose($fp);

    return TRUE;
}

function strip_comment($address)
{
    $comment = "/\\([^()]*\\)/";
    while (preg_match($comment, $address)) {
        $address = preg_replace($comment, "", $address);
    }

    return $address;
}

function get_address($address)
{
    $address = preg_replace("/([ \t\r\n])+/", "", $address);
    $address = preg_replace("/^.*&lt;(.+)&gt;.*$/", "\\1", $address);

    return $address;
}

function smtp_debug($message)
{
    if ($this-&gt;debug) {
        echo $message . "&lt;br&gt;";
    }
}

function get_attach_type($image_tag)
{ //

    $filedata = array();

    $img_file_con = fopen($image_tag, "r");
    unset($image_data);
    while ($tem_buffer = AddSlashes(fread($img_file_con, filesize($image_tag))))
        $image_data = $tem_buffer;
    fclose($img_file_con);

    $filedata['context'] = $image_data;
    $filedata['filename'] = basename($image_tag);
    $extension = substr($image_tag, strrpos($image_tag, "."), strlen($image_tag) - strrpos($image_tag, "."));
    switch ($extension) {
        case ".gif":
            $filedata['type'] = "image/gif";
            break;
        case ".gz":
            $filedata['type'] = "application/x-gzip";
            break;
        case ".htm":
            $filedata['type'] = "text/html";
            break;
        case ".html":
            $filedata['type'] = "text/html";
            break;
        case ".jpg":
            $filedata['type'] = "image/jpeg";
            break;
        case ".tar":
            $filedata['type'] = "application/x-tar";
            break;
        case ".txt":
            $filedata['type'] = "text/plain";
            break;
        case ".zip":
            $filedata['type'] = "application/zip";
            break;
        default:
            $filedata['type'] = "application/octet-stream";
            break;
    }
    return $filedata;
}
`
} // end class
?> 

DEBUG

smtp.class.php 发信类+最新可用+支持 PHP7

成功截图

smtp.class.php 发信类+最新可用+支持 PHP7

问题

期间曾浪费了我一些时间,总是发信不了,显示连接失败,本以为账号密码问题,但是检查了好几次确认无误,报错信息:
Trying to smtp.qq.com:465 Error: Remote host returned "" Error: Cannot

我的解决方法是将 $smtpserver = "smtp.qq.com"; 改成 $smtpserver = "ssl://smtp.qq.com"; 即可解决成功连接。

打包下载

SMTP DEMO

赞(0)
未经允许不得转载:工具盒子 » smtp.class.php 发信类+最新可用+支持 PHP7