PHP門面模式實現(xiàn)簡單的郵件發(fā)送示例
前言:
門面模式屬于設(shè)計模式中三大分類之一的結(jié)構(gòu)類型,也叫外觀模式。其作用對客戶端低耦合底層功能的封裝,客戶端不用知道子系統(tǒng)間的調(diào)用。
舉例:
門面模式就相當(dāng)于電腦主機(jī),用戶要打開某個應(yīng)用程序,只需要知道兩步。打開開機(jī)按鈕,電腦開機(jī)后再打開應(yīng)用。開機(jī)按鈕就相當(dāng)于一個門面,里面的開機(jī)需要調(diào)用不同的模塊,比如硬件自檢,選擇啟動盤,加載引導(dǎo),加載內(nèi)核,OS初始化,啟動指定級任務(wù)等,以下也通過發(fā)郵件的例子描述門面一模式。

涉及:
- call_user_func函數(shù)的使用
- 異常類的自定義處理
- 類的分層封裝
- 發(fā)郵件功能的實現(xiàn)與配置
編碼:
- 必須先composer require phpmailer/phpmailer安裝依賴庫。
- 創(chuàng)建擴(kuò)展類目錄,里面包括獨立的配置文件,門面角色類,郵件功能類,校驗類,異常類。

3. 獨立的配置類,包括smtp服務(wù)地址,端口,中轉(zhuǎn)郵箱賬號,授權(quán)碼,郵件發(fā)送者昵稱(唯一標(biāo)識)。
<?php
/**
* @Notes: 郵箱SMTP服務(wù)配置
* @Interface getCondition
* @Return mixed
* @Author: bqs
* @Time: 2020/8/31 10:15
*/
return [
'smtp_server' => 'smtp.qq.com', // QQ郵箱開啟的smtp
'smtp_port' => 465, // QQsmtp服務(wù)端口
'smtp_user' => '2652364582@qq.com', // 北橋蘇郵箱
'smtp_pwd' => 'ynxdedefduuhecbj', // SMTP服務(wù)開啟后授權(quán)碼
'email_id' => '酷D' // 郵件發(fā)送者的唯一標(biāo)識(自定義的昵稱)
];- 門面角色類,也就是客戶直接調(diào)用的,只有一個發(fā)送方法,但是該方法需要調(diào)用校驗和實際發(fā)送的方法實現(xiàn)。
<?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: 面向客戶的郵件發(fā)送調(diào)用
* @Author: bqs
* @Time: 2020/8/31 13:33
* @Interface send
* @param $params
* @Return boolean 成功|失敗
*/
private function send($params)
{
// 校驗參數(shù)
$validate = Validate::make(__FUNCTION__);
$res = $validate->check($params);
if (!$res) {
// 拋出自定義異常
throw new MailException($validate->getError(),422);
return false;
}
// 發(fā)送郵件
$mail = new Mail();
$res = $mail->send($params);
return $res;
}
}- 自定義異常類,可以在門面角色中以該類拋出,然后在客戶調(diào)用中以該類捕捉,以下自定義了錯誤消息的輸出。
<?php
/**
* @Notes: 郵件發(fā)送校驗器
* @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();
}
}校驗器,主要判斷客戶調(diào)用傳入的參數(shù)。
<?php
/**
* @Notes: 郵件發(fā)送校驗器
* @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;
}
// 創(chuàng)建驗證器對象
public static function make($type)
{
return new self($type);
}
// 與實際傳入的參數(shù)做校驗
public function check($params = [])
{
if (empty($params)) {
$this->error = "參數(shù)不足,非法請求";
}
$this->error = call_user_func([new self($this->type),$this->type],$params);
return $this->error ? false : true;
}
// 發(fā)送參數(shù)校驗
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 "郵箱格式不正確";
}
}
// 郵件標(biāo)題
if (!isset($params[1]) || !$params[1]) {
return "郵件標(biāo)題不能為空";
}
if (!isset($params[2]) || !$params[2]) {
return "郵件內(nèi)容不能為空";
}
return $res;
}
// 獲取錯誤信息
public function getError()
{
return $this->error;
}
}- 實際的郵件發(fā)送,需要使用phpmail庫。
<?php
/**
* @Notes: 郵件實際發(fā)送
* @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: 發(fā)郵件
* @Author: bqs
* @Time: 2020/8/31 13:07
* @Interface send
* @Return mixed
*/
public function send($params)
{
$to = $params[0]; // 接收者
$subject = $params[1]; // 郵件標(biāo)題
$content = $params[2]; // 郵件內(nèi)容
$emails = new PHPMailer();
$emails->CharSet = 'UTF-8'; //設(shè)定郵件編碼,默認(rèn)ISO-8859-1,如果發(fā)中文此項必須設(shè)置,否則亂碼
$emails->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$emails->SMTPDebug = 0;
//調(diào)試輸出格式
//$emails->Debugoutput = 'html';
//smtp服務(wù)器
$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';// 使用安全協(xié)議
//Whether to use SMTP authentication
$emails->SMTPAuth = true;
//發(fā)送郵箱
$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']);
//回復(fù)地址
//$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
//標(biāo)題
$emails->Subject = $subject;
//HTML內(nèi)容轉(zhuǎn)換
$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();
}
}- 客戶調(diào)用部分。
public function sendMail()
{
try {
$res = \mail\MailFacade::send(["1641181271@qq.com"], "測試標(biāo)題", "測試內(nèi)容");
var_dump($res);
die;
} catch (MailException $e) { // 捕捉自定義異常類拋出
var_dump($e->errorMessage());
die;
} catch (\Exception $e) {
var_dump($e->getMessage());
die;
}
}- 返回true后查看郵件是否接收。
環(huán)境要求:
實現(xiàn)郵件發(fā)送是需要特定的環(huán)境和相關(guān)的配置才能實現(xiàn),以下就以實現(xiàn)成功發(fā)送補(bǔ)充的操作。
第一步:打開網(wǎng)址下載PHPMailer,PHPMailer 需要 PHP 的 sockets 擴(kuò)展支持,而登錄 QQ 郵箱 SMTP 服務(wù)器則必須通過 SSL 加密的, PHP 還得包含 openssl 的支持。

第二步:使用 phpinfo() 函數(shù)查看 socket 和 openssl 擴(kuò)展信息(wamp server 默認(rèn)啟用了該擴(kuò)展)。openssl 如果沒有開啟請打開php.ini文件進(jìn)行開啟首先檢查php.ini中;extension=php_openssl.dll是否存在, 如果存在的話去掉前面的注釋符‘;’, 如果不存在這行,那么添加extension=php_openssl.dll。

PHPMailer 核心文件

第三步:**QQ 郵箱設(shè)置所有的主流郵箱都支持 SMTP 協(xié)議,但并非所有郵箱都默認(rèn)開啟,您可以在郵箱的設(shè)置里面手動開啟。第三方服務(wù)在提供了賬號和密碼之后就可以登錄 SMTP 服務(wù)器,通過它來控制郵件的中轉(zhuǎn)方式。
第四步:開啟 SMTP 服務(wù)

選擇 IMAP/SMTP 服務(wù),點擊開啟服務(wù) 第五步:驗證密保

發(fā)送短信“配置郵件客戶端”至1069-0700-69 第六步:獲取授權(quán)碼

SMTP 服務(wù)器認(rèn)證密碼,也就是授權(quán)碼,使用的時候沒有空格,需要妥善保管。
以上就是PHP門面模式實現(xiàn)簡單的郵件發(fā)送示例的詳細(xì)內(nèi)容,更多關(guān)于PHP門面模式發(fā)送郵件的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
PHP實現(xiàn)移除數(shù)組中為空或為某值元素的方法
這篇文章主要介紹了PHP實現(xiàn)移除數(shù)組中為空或為某值元素的方法,涉及php使用array_filter過濾數(shù)組的相關(guān)操作技巧,需要的朋友可以參考下2017-01-01
PHP使用stream_context_create()模擬POST/GET請求的方法
這篇文章主要介紹了PHP使用stream_context_create()模擬POST/GET請求的方法,結(jié)合實例形式較為詳細(xì)的分析了stream_context_create模擬POST/GET請求的原理,使用方法與相關(guān)注意事項,需要的朋友可以參考下2016-04-04
php array_map與array_walk比較案例詳解
這篇文章主要介紹了php array_map與array_walk比較案例詳解,本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-09-09

