一、163邮件工厂开发
1、添加框架对应的SDK
composer require phpmailer/phpmailer
2、添加163邮件工厂
在根目录下extend文件夹下Mail文件夹下channel文件夹下,创建163邮件发送工厂并命名为WangyiMailSender。记住,一定要在163邮件发送工厂类名后面去实现邮件发送工厂。
<?php
/**
* 网易163邮件发送类
* User: 龙哥·三年风水
* Date: 2024/12/5
* Time: 15:23
*/
namespace Mail\channel;
use Mail\MailSenderInterface;
use Error\BaseError;
use PHPMailer\PHPMailer\PHPMailer;
use app\model\param\Mail;
class WangyiMailSender implements MailSenderInterface
{
protected static $host = '';// 发送人的SMTP服务器地址
protected static $charSet = 'utf8';// 编码格式为utf8,不设置编码的话,中文会出现乱码
protected static $recipient = '';// 收件人
protected static $username = '';// 发件人
protected static $password = '';// 发送方的邮箱密码,注意这里填写的是“客户端授权密码”而不是邮箱的登录密码!
protected static $stmpSecure = '';// 使用ssl协议方式
protected static $port = 0;// ssl协议方式端口号是465
protected static $phpMailer = null;// 邮件发送客户端
public function __construct($param){
$res = Mail::dataFind(['id' => $param['mail_id']],'username,smtp_address,smtp_port,smtp_password,smtp_protocol,status',true);
if(empty($res))throw new BaseError("未开启163邮件发送通道",50000,200);
if($res['status'] == 0)throw new BaseError("163邮件发送通道已被禁用",50000,200);
self::$host = $res['smtp_address'];
self::$port = $res['smtp_port'];
self::$password = $res['smtp_password'];
self::$stmpSecure = $res['smtp_protocol'];
self::$recipient = $param['recipient'];
self::$username = $res['username'];
self::$phpMailer = new PHPMailer(true);
}
/**
* 单个邮件发送
* User: 龙哥·三年风水
* Date: 2024/12/5
* Time: 14:29
* @ param $emailSubject 邮件主题
* @ param $emailContent 邮件内容
* @ param string $emailAttachment 邮件附件
* @ return mixed
*/
public static function send($emailSubject, $emailContent, $emailAttachment = '')
{
self::$phpMailer->isSMTP();// 使用SMTP服务
self::$phpMailer->CharSet = self::$charSet;// 编码格式为utf8,不设置编码的话,中文会出现乱码
self::$phpMailer->Host = self::$host;// 发送人的SMTP服务器地址
self::$phpMailer->SMTPAuth = true;// 是否使用身份验证
self::$phpMailer->Username = self::$username;// SMTP账号
self::$phpMailer->Password = self::$password;// SMTP密码
self::$phpMailer->SMTPSecure = self::$stmpSecure;// 使用ssl协议方式
self::$phpMailer->Port = self::$port;// ssl协议方式端口号是465
self::$phpMailer->setFrom(self::$username,$emailSubject);// 设置发件人信息,如邮件格式说明中的发件人,这里会显示为
self::$phpMailer->addAddress(self::$recipient,$emailSubject);// 设置收件人信息,如邮件格式说明中的收件人
if(!empty($emailAttachment))self::$phpMailer->addAttachment($emailAttachment);// 添加附件
self::$phpMailer->isHTML(true);
self::$phpMailer->Subject = $emailSubject;
self::$phpMailer->Body = $emailContent;
if(self::$phpMailer->send() == false)throw new BaseError("163邮件发送失败:".self::$phpMailer->ErrorInfo,50000,200);
return true;
}
}
二、测试
<?php
namespace app\controller;
use Encipher\Encrypt;
use Mail\MailSenderFactory;
use Sms\SmsSenderFactory;
class Index extends Emptys
{
public function index()
{
$emailSender = MailSenderFactory::create('15056985491@163.com');
$emailSender::send('运维发送','IP更改');
return succ('操作成功');
}
}