ThinkPHP\Library\composer.json文件 加入 "phpmailer/phpmailer": "^6.0" 然後運行一下
沒有安裝composer的自行安裝一下 , 這裏不多說了
Application 下創建 lib目錄 Sendmail.class.php 文件
<?php
namespace Lib;
class Sendmail
{
public static $HOST = 'smtp.qq.com'; // QQ 郵箱的服務器地址 163等都行
public static $PORT = 465; // smtp 服務器的遠程服務器端口號
public static $SMTP = 'ssl'; // 使用 ssl 加密方式登錄
public static $CHARSET = 'UTF-8'; // 設置發送的郵件的編碼
private static $USERNAME = '[email protected]'; // 授權登錄的賬號
private static $PASSWORD = '1233'; // 授權登錄的密碼 授權碼去郵箱裏面申請
private static $NICKNAME = '1233'; // 發件人的暱稱
/**
* QQMailer constructor.
*
* @param bool $debug [調試模式]
*/
public function __construct($debug = false)
{
vendor('autoload', '', '.php'); //引入自動加載類,用於加載第三方類庫
$this->mailer = new \PHPMailer\PHPMailer\PHPMailer();
$this->mailer->SMTPDebug = $debug ? 1 : 0;
$this->mailer->isSMTP(); // 使用 SMTP 方式發送郵件
}
/**
* @return PHPMailer
*/
public function getMailer()
{
return $this->mailer;
}
private function loadConfig()
{
/* Server Settings */
$this->mailer->SMTPAuth = true; // 開啓 SMTP 認證
$this->mailer->Host = self::$HOST; // SMTP 服務器地址
$this->mailer->Port = self::$PORT; // 遠程服務器端口號
$this->mailer->SMTPSecure = self::$SMTP; // 登錄認證方式
/* Account Settings */
$this->mailer->Username = self::$USERNAME; // SMTP 登錄賬號
$this->mailer->Password = self::$PASSWORD; // SMTP 登錄密碼
$this->mailer->From = self::$USERNAME; // 發件人郵箱地址
$this->mailer->FromName = self::$NICKNAME; // 發件人暱稱(任意內容)
/* Content Setting */
$this->mailer->isHTML(true); // 郵件正文是否爲 HTML
$this->mailer->CharSet = self::$CHARSET; // 發送的郵件的編碼
}
/**
* Add attachment.
*
* @param $path [附件路徑]
*/
public function addFile($path)
{
$this->mailer->addAttachment($path);
}
/**
* Send Email.
*
* @param $email [收件人]
* @param $title [主題]
* @param $content [正文]
*
* @return bool [發送狀態]
*/
public function send($email, $title, $content)
{
$this->loadConfig();
if (is_array($email)) {
foreach ($email as $v) {
$this->mailer->addAddress($v); // 收件人郵箱
}
} else {
$this->mailer->addAddress($email); // 收件人郵箱
}
// var_dump($this->mailer);die;
$this->mailer->Subject = $title; // 郵件主題
$this->mailer->Body = $content; // 郵件信息
return (bool) $this->mailer->send(); // 發送郵件
}
}
然後 EmailController 控制器 可以基於send方法來封裝很多實用的功能啦
<?php
namespace Api\Controller;
class EmailController extends BaseController
{
//收件人 標題 內容 附件
public function send($target, $title, $content, $filepath='')
{
$mail = new \Lib\Sendmail();
$filepath && $mail->addFile($filepath); //添加附件
$re = $mail->send($target, $title, $content); //收件人 郵件名稱 內容
return $re;
}
}