关于PHP发送邮件的两个类(找了好久......)

需要用PHP发送邮件,不想要PHPmailer那么复杂,找来找去,总算找到了一个好用的,分享出来,PHP邮件发送类,一共包含两个文件.代码如下:

sent_mail.php

<?php
require_once('email.class.php');
//##########################################
$smtpserver = "smtp.163.com";//SMTP服务器
$smtpserverport = 25;//SMTP服务器端口
$smtpusermail = "*********@163.com";//SMTP服务器的用户邮箱
$smtpemailto = "*********@qq.com";//发送给谁
$smtpuser = "*********@163.com";//SMTP服务器的用户帐号
$smtppass = "********";//SMTP服务器的用户密码
$mailsubject = "PHP测试邮件系统";//邮件主题
$mailbody = "<h1> 这是一个测试程序</h1>";//邮件内容
$mailtype = "HTML";//邮件格式(HTML/TXT),TXT为文本邮件
##########################################
$smtp = new smtp($smtpserver, $smtpserverport, true, $smtpuser, $smtppass);//这里面的一个true是表示使用身份验证,否则不使用身份验证.
$smtp->debug = true;//是否显示发送的调试信息
$smtp->sendmail($smtpemailto, $smtpusermail, $mailsubject, $mailbody, $mailtype);
?>

email.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->debug = FALSE;
        $this->smtp_port = $smtp_port;
        $this->relay_host = $relay_host;
        $this->time_out = 30; //is used in fsockopen()
        #
        $this->auth = $auth;//auth
        $this->user = $user;
        $this->pass = $pass;
        #
        $this->host_name = "localhost"; //is used in HELO command
        $this->log_file = "";

        $this->sock = FALSE;
    }

    /* Main Function */
    function sendmail($to, $from, $subject = "", $body = "", $mailtype, $cc = "", $bcc = "", $additional_headers = "")
    {
        $mail_from = $this->get_address($this->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<" . $from . ">\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: <" . date("YmdHis", $sec) . "." . ($msec * 1000000) . "." . $mail_from . ">\r\n";
        $TO = explode(",", $this->strip_comment($to));

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

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

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

    /* Private Functions */

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

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

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

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

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

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

        return TRUE;
    }

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

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

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

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

        return TRUE;
    }

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

        return $this->smtp_ok();
    }

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

        if (!preg_match("/^[23]/", $response)) {
            fputs($this->sock, "QUIT\r\n");
            fgets($this->sock, 512);
            $this->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->sock, $cmd . "\r\n");
        $this->smtp_debug("> " . $cmd . "\n");

        return $this->smtp_ok();
    }

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

    function log_write($message)
    {
        $this->smtp_debug($message);

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

        $message = date("M d H:i:s ") . get_current_user() . "[" . getmypid() . "]: " . $message;
        if ([email protected]_exists($this->log_file) || !($fp = @fopen($this->log_file, "a"))) {
            $this->smtp_debug("Warning: Cannot open log file \"" . $this->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("/^.*<(.+)>.*$/", "\\1", $address);

        return $address;
    }

    function smtp_debug($message)
    {
        if ($this->debug) {
            echo $message . "<br>";
        }
    }

    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
?> 

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-10-11 12:05:09

关于PHP发送邮件的两个类(找了好久......)的相关文章

奇葩问题:spring+mybaits项目突然出现其中一些Mapper类找不到

一.问题现象 1,No bean named 'bomManageMapper' found in org.s[email protected]......... 2,我把代码中引用的bomManageMapper全部注释掉,又会出现另外一个Mapper对象找不到 3,但是奇怪的是,有两个项目启动的时用到的Mapper对象可以找到,发现这两个Mapper对象是在项目的core包下面,而其他找不到的Mapper对象都在interfaces包下面: 二.寻找答案 1,怀疑是昨天修改了什么东西,导致的

【转】 C++中两个类相互包含引用问题

原文:http://blog.csdn.net/leo115/article/details/7395077 在构造自己的类时,有可能会碰到两个类之间的相互引用问题,例如:定义了类A类B,A中使用了B定义的类型,B中也使用了A定义的类型 class A { int i; B b; } class B { int i; A* a; } 请注意上面的定义内容,一般情况下是不能出现类A,类B相互引用都定义对象,即如下的样子: class A { int i; B b; } class B { int

类找不到异常 Caused by: java.lang.NoClassDefFoundError

错误原因:在部署应用的时候,服务器报错,Caused by: java.lang.ClassNotFoundException: org.quartz.impl.JobDetailImpl,某个类找不到,找到对应的包发现明明某个jar已经引进去了,在仔细一看发现有三个类似的jar, com.alibaba.external:opensymphony.quartz,opensymphony:quartz,org.quartz-scheduler:quartz.实际上我希望的包,是org.quart

关于Android项目中,突然就R类找不到已存在的资源文件的解决方法

项目代码早上打开正常,下午开的时候突然提示R类找不到已存在的布局文件,于是试了各种方法,CLEAN啊,重启啊,均无效,然后去网上搜了下,遇到这个问题的人还不少. 看到其中有这么一条解决方法,删除导入的Android.R包,去检查了自己的代码,果然有这么一行,删除之后,问题解决. 但是又比较奇怪这个Android.R是什么东西,得到的答复是,是系统的资源类,如果导入之后会与本地工程文件的R类冲突,所以产生错误,找不到布局文件等问题. 希望能对大家有所帮助.

Single Number 数组中除了某个元素出现一次,其他都出现两次,找出这个元素

Given an array of integers, every element appears twice except for one. Find that single one. Note:Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 数组中除了某个元素出现一次,其他都出现两次,找出只出现一次的元素. 一个数字和自己异或

遇到一个spring启动时类找不到的问题~

今天将一个老的项目部署到Tomcat7上运行时,spring初始化一直失败,提示错误如下: Java.lang.NoClassDefFoundError:org.springframework.beans.FatalBeanException 控制台打印的堆栈信息如下: [org.springframework.web.context.ContextLoader]-[ERROR] Context initialization failed java.lang.NoClassDefFoundErr

C++中两个类互相引用的解决方法

一.问题描述 现在有两个类A和B需要定义,定义A的时候需要用到B,定义B的时候需要用到A. 二.分析 A和B的定义和调用都放在一个文件中肯定是不可以的,这样就会造成两个循环调用的死循环. 根本原因是:定义A的时候,A的里面有B,所以就需要去查看B的占空间大小,但是查看的时候又发现需要知道A的占空间大小,造成死循环. 解决方法1: (1)写两个头文件A.h和B.h分别用于声明类A和B: (2)写两个.cpp文件分别用于定义类A和B: (3)在A和B的头文件中分别导入对方的头文件. 解决方法2: (

给html5引擎lufylegend添加了两个类LTimer和LMovieClip

项目中经常用到as3中Timer和MovieClip类似的功能,但都时间整理,今天花半天时间仿照as3文档写了这两个类,感觉还不错,LTimer已经测试完成,LMovieClip已完成编码但还没测试,明天抽空测试一下就提交给lufy.有了这两个,开发项目将会方便许多.

类名不同,结构相同的两个类相互转换

类名不同,结构相同的两个类相互转换,忽略 实体null值的json转换: /// <summary> /// 结构相同,类名不同的实体类转换(忽略 null /// kk 2015-06-03 /// </summary> /// <typeparam name="T">需转换的类 类型</typeparam> /// <typeparam name="V">目标类 类型</typeparam>