美文网首页
tp5 使用邮箱发送功能 PHPMailer

tp5 使用邮箱发送功能 PHPMailer

作者: peterz博客 | 来源:发表于2019-03-24 22:32 被阅读0次

    PHPMailer

    PHPMailer 是一个封装好的 PHP 邮件发送类,支持发送 HTML 内容的电子邮件,以及可以添加附件发送,并不像 PHP 本身 mail() 函数需要服务器环境支持,您只需要设置邮件服务器以相关信息就能实现邮件发送功能。

    PHP扩展支持

    PHPMailer 需要 PHP 的 sockets 扩展支持,而登录 QQ 邮箱 SMTP 服务器则必须通过 SSL 加密,故 PHP 还得包含 openssl 的支持。

    image.png
    以qq邮箱为例
    1、开启IMAP/SMTP服务

    登录qq邮箱,首先需要开启邮箱的SMTP服务。
    找到qq邮箱>设置>账户>POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务

    image.png

    开启之后,要记得生成授权码,授权码一定要是最新的。

    2、安装phpmailer

    (1)composer 安装
    composer require phpmailer/phpmailer
    或者在composer.json中手动增加一个 phpmailer require

    "require": {
            "php": ">=5.4.0",
            "phpmailer/phpmailer": "^5.2"
        },
    

    (2) 或者gitHub 下载 https://github.com/PHPMailer/PHPMailer
    (3)或官网下载 https://sourceforge.net/projects/phpmailer/files/latest/download

    3、配置参数

    为了分便使用可以把配置函数写到common.php公共函数文件中如

     /**
      * 配置youji
      */
    function SendMail($address,$title,$message){
        vendor ('phpmailer.phpmailer.src.PHPMailer');
        $mail = new \PHPMailer();
         // 设置PHPMailer使用SMTP服务器发送Email
        $mail->IsSMTP();
        // 设置邮件的字符编码,若不指定,则为'UTF-8'
        $mail->CharSet='UTF-8';
        // 添加收件人地址,可以多次使用来添加多个收件人
        $mail->AddAddress($address);
        // 设置邮件正文
        $mail->Body=$message;
        //设置发件人邮箱地址 这里填入上述提到的“发件人邮箱”
        $mail->From='***@qq.com';
        //设置发件人姓名(昵称) 任意内容,显示在收件人邮件的发件人邮箱地址前的发件人姓名
        $mail->FromName='皮特张';
        // 设置邮件标题
        $mail->Subject=$title;
        // 设置SMTP服务器。
        $mail->Host='smtp.qq.com';
        // 设置为"需要验证"
        $mail->SMTPAuth=true;
        //smtp登录的账号 这里填入字符串格式的qq号即可
        $mail->Username='****';
        //smtp登录的密码 使用生成的授权码 你的最新的授权码
        $mail->Password='*********';
        // 发送邮件。    成功返回true或false
       return($mail->Send());
    }
    
        /**
         * 调用发送邮件
         */
        public function testmailer(){
            $res = $this->SendMail('***@qq.com','发送标题','发送成功了耶');
            if(!$res){
                return $this->error('发送邮件失败');
            }
            return $this->success('发送邮件成功','/');
        }
    
    4、发送成功
    image.png

    相关文章

      网友评论

          本文标题:tp5 使用邮箱发送功能 PHPMailer

          本文链接:https://www.haomeiwen.com/subject/rnbpvqtx.html