关于php:以PHP门面模式实现简单的邮件发送

4次阅读

共计 5177 个字符,预计需要花费 13 分钟才能阅读完成。

前言:

门面模式属于设计模式中三大分类之一的构造类型,也叫外观模式。其作用对客户端低耦合底层性能的封装,客户端不必晓得子系统间的调用。

举例:

门面模式就相当于电脑主机,用户要关上某个应用程序,只须要晓得两步。关上开机按钮,电脑开机后再关上利用。开机按钮就相当于一个门面,外面的开机须要调用不同的模块,比方硬件自检,抉择启动盘,加载疏导,加载内核,OS 初始化,启动指定级任务等,以下也通过发邮件的例子形容门面一模式。

波及:

  1. call_user_func 函数的应用
  2. 异样类的自定义解决
  3. 类的分层封装
  4. 发邮件性能的实现与配置 

编码:

  1. 必须先 composer require phpmailer/phpmailer 装置依赖库。
  2. 创立扩大类目录,外面包含独立的配置文件,门面角色类,邮件性能类,校验类,异样类。

3. 独立的配置类,包含 smtp 服务地址,端口,直达邮箱账号,受权码,邮件发送者昵称 (惟一标识)。

<?php
/**
 * @Notes: 邮箱 SMTP 服务配置
 * @Interface getCondition
 * @Return mixed
 * @Author: bqs
 * @Time: 2020/8/31 10:15
 */

return [
    'smtp_server' => 'smtp.qq.com',                     // QQ 邮箱开启的 smtp
    'smtp_port' => 465,                                 // QQsmtp 服务端口
    'smtp_user' => '2652364582@qq.com',                 // 北桥苏邮箱
    'smtp_pwd' => 'ynxdedefduuhecbj',                   // SMTP 服务开启后受权码
    'email_id' => '酷 D'                                 // 邮件发送者的惟一标识 (自定义的昵称)
];
  1. 门面角色类,也就是客户间接调用的,只有一个发送办法,然而该办法须要调用校验和理论发送的办法实现。
<?php
/**
 * @Notes: 邮件门面
 * @Interface getCondition
 * @Return mixed
 * @Author: bqs
 * @Time: 2020/8/31 13:10
 */

namespace mail;

use think\Container;
use mail\facade\MailException;
use mail\facade\Mail;
use mail\facade\Validate;

class MailFacade
{

    protected $error;

    public static function __callStatic($method, $params)
    {//return (new static)->{$method}(...$params);
        return call_user_func([new MailFacade(),$method],$params);
    }

    /**
     * @Notes: 面向客户的邮件发送调用
     * @Author: bqs
     * @Time: 2020/8/31 13:33
     * @Interface send
     * @param $params
     * @Return boolean 胜利 | 失败
     */
    private function send($params)
    {
        // 校验参数
        $validate = Validate::make(__FUNCTION__);

        $res = $validate->check($params);

        if (!$res) {
            // 抛出自定义异样
            throw new MailException($validate->getError(),422);
            return false;
        }

        // 发送邮件
        $mail = new Mail();
        $res = $mail->send($params);

        return $res;
    }

}
  1. 自定义异样类,能够在门面角色中以该类抛出,而后在客户调用中以该类捕获,以下自定义了谬误音讯的输入。
<?php
/**
 * @Notes: 邮件发送校验器
 * @Interface getCondition
 * @Return mixed
 * @Author: bqs
 * @Time: 2020/8/31 13:03
 */

namespace mail\facade;


class MailException extends \Exception
{public function errorMessage()
    {return "mail error:".$this->getMessage();
    }

}
  1. 校验器,次要判断客户调用传入的参数。

    <?php
    /**
     * @Notes: 邮件发送校验器
     * @Interface getCondition
     * @Return mixed
     * @Author: bqs
     * @Time: 2020/8/31 13:03
     */
    
    namespace mail\facade;
    
    class Validate
    {
     protected $error;
    
     protected $type;        // 办法名
    
     public function __construct($type)
     {$this->type = $type;}
    
     // 创立验证器对象
     public static function make($type)
     {return new self($type);
     }
    
     // 与理论传入的参数做校验
     public function check($params = [])
     {if (empty($params)) {$this->error = "参数有余, 非法申请";}
    
         $this->error = call_user_func([new self($this->type),$this->type],$params);
    
         return $this->error ? false : true;
     }
    
     // 发送参数校验
     public function send($params)
     {
         $res = "";
    
         // 邮件
         if (!isset($params[0]) || empty($params[0])) {return "邮箱不能为空";}
    
         $email = [];
         if (is_array($params[0])) {$email = $params[0];
         }else {$email[0] = $params[0];
         }
    
         foreach ($email as $key => $val) {if (!preg_match("/^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/",$val)) {return "邮箱格局不正确";}
         }
    
         // 邮件题目
         if (!isset($params[1]) || !$params[1]) {return "邮件题目不能为空";}
    
         if (!isset($params[2]) || !$params[2]) {return "邮件内容不能为空";}
    
         return $res;
     }
    
     // 获取错误信息
     public function getError()
     {return $this->error;}
    
    }
  2. 理论的邮件发送,须要应用 phpmail 库。
<?php
/**
 * @Notes: 邮件理论发送
 * @Interface getCondition
 * @Return mixed
 * @Author: bqs
 * @Time: 2020/8/31 13:03
 */

namespace mail\facade;

use PHPMailer\PHPMailer\PHPMailer;

class Mail
{protected $config = [];

    public function __construct()
    {$this->config = include(dirname(__DIR__) . "../config/mail_config.php");
    }

    /**
     * @Notes: 发邮件
     * @Author: bqs
     * @Time: 2020/8/31 13:07
     * @Interface send
     * @Return mixed
     */
    public function send($params)
    {$to = $params[0];                       // 接收者
        $subject = $params[1];                  // 邮件题目
        $content = $params[2];                  // 邮件内容

        $emails = new PHPMailer();

        $emails->CharSet = 'UTF-8'; // 设定邮件编码,默认 ISO-8859-1,如果发中文此项必须设置,否则乱码
        $emails->isSMTP();

        //Enable SMTP debugging
        // 0 = off (for production use)
        // 1 = client messages
        // 2 = client and server messages
        $emails->SMTPDebug = 0;

        // 调试输入格局
        //$emails->Debugoutput = 'html';
        //smtp 服务器
        $emails->Host = $this->config['smtp_server'];

        // 端口 - likely to be 25, 465 or 587
        $emails->Port = $this->config['smtp_port'];

        if ($emails->Port === 465) $emails->SMTPSecure = 'ssl';// 应用平安协定
        //Whether to use SMTP authentication
        $emails->SMTPAuth = true;
        // 发送邮箱
        $emails->Username = $this->config['smtp_user'];
        // 明码
        $emails->Password = $this->config['smtp_pwd'];
        //Set who the message is to be sent from
        $emails->setFrom($this->config['smtp_user'], $this->config['email_id']);

        // 回复地址
        //$emails->addReplyTo('replyto@example.com', 'First Last');

        // 接管邮件方
        if (is_array($to)) {foreach ($to as $v) {$emails->addAddress($v);
            }

        } else {$emails->addAddress($to);
        }

        $emails->isHTML(true);// send as HTML

        // 题目
        $emails->Subject = $subject;

        //HTML 内容转换
        $emails->msgHTML($content);

        //Replace the plain text body with one created manually
        //$emails->AltBody = 'This is a plain-text message body';

        // 增加附件
        //$emails->addAttachment('images/phpmailer_mini.png');
        //send the message, check for errors

        return $emails->send();}

}
  1. 客户调用局部。
public function sendMail()
    {

        try {$res = \mail\MailFacade::send(["1641181271@qq.com"], "测试题目", "测试内容");

            var_dump($res);
            die;

        } catch (MailException $e) {                // 捕获自定义异样类抛出

            var_dump($e->errorMessage());
            die;

        } catch (\Exception $e) {var_dump($e->getMessage());
            die;
        }

    }
  1. 返回 true 后查看邮件是否接管。

环境要求:

实现邮件发送是须要特定的环境和相干的配置能力实现,以下就以实现胜利发送补充的操作。

第一步:关上网址下载 PHPMailer,PHPMailer 须要 PHP 的 sockets 扩大反对,而登录 QQ 邮箱 SMTP 服务器则必须通过 SSL 加密的,PHP 还得蕴含 openssl 的反对。

 第二步:应用 phpinfo() 函数查看 socket 和 openssl 扩大信息(wamp server 默认启用了该扩大)。openssl 如果没有开启请关上 php.ini 文件进行开启首先查看 php.ini 中;extension=php_openssl.dll 是否存在,如果存在的话去掉后面的正文符‘;’,如果不存在这行,那么增加 extension=php_openssl.dll。

PHPMailer 外围文件

 第三步:**QQ 邮箱设置所有的支流邮箱都反对 SMTP 协定,但并非所有邮箱都默认开启,您能够在邮箱的设置外面手动开启。第三方服务在提供了账号和明码之后就能够登录 SMTP 服务器,通过它来管制邮件的直达形式。

第四步:开启 SMTP 服务

抉择 IMAP/SMTP 服务,点击开启服务 第五步:验证密保

发送短信“配置邮件客户端”至 1069-0700-69 第六步:获取受权码

SMTP 服务器认证明码,也就是受权码,应用的时候没有空格,须要妥善保存。

正文完
 0