PHP門面模式實現簡單的郵件發送示例
門面模式屬于設計模式中三大分類之一的結構類型,也叫外觀模式。其作用對客戶端低耦合底層功能的封裝,客戶端不用知道子系統間的調用。
舉例:門面模式就相當于電腦主機,用戶要打開某個應用程序,只需要知道兩步。打開開機按鈕,電腦開機后再打開應用。開機按鈕就相當于一個門面,里面的開機需要調用不同的模塊,比如硬件自檢,選擇啟動盤,加載引導,加載內核,OS初始化,啟動指定級任務等,以下也通過發郵件的例子描述門面一模式。
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' => '[email protected]', // 北橋蘇郵箱 'smtp_pwd' => 'ynxdedefduuhecbj', // SMTP服務開啟后授權碼 'email_id' => '酷D' // 郵件發送者的唯一標識(自定義的昵稱)];門面角色類,也就是客戶直接調用的,只有一個發送方法,但是該方法需要調用校驗和實際發送的方法實現。<?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; }}自定義異常類,可以在門面角色中以該類拋出,然后在客戶調用中以該類捕捉,以下自定義了錯誤消息的輸出。<?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(); }}校驗器,主要判斷客戶調用傳入的參數。
<?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; }}實際的郵件發送,需要使用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('[email protected]', '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 errorsreturn $emails->send(); }}客戶調用部分。public function sendMail() {try { $res = \mail\MailFacade::send(['[email protected]'], '測試標題', '測試內容'); var_dump($res); die;} catch (MailException $e) {// 捕捉自定義異常類拋出 var_dump($e->errorMessage()); die;} catch (\Exception $e) { var_dump($e->getMessage()); die;} }返回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 服務器認證密碼,也就是授權碼,使用的時候沒有空格,需要妥善保管。
以上就是PHP門面模式實現簡單的郵件發送示例的詳細內容,更多關于PHP門面模式發送郵件的資料請關注好吧啦網其它相關文章!