用到的库:swoole , PHPMailer , thinkphp5
用SWOOLE 新建一个服务
namespace app\common\service;class EmailService{public function email_server(){$serv = new \swoole_server('127.0.0.1',8122);$serv->set(array('task_worker_num' => 4));$serv->on('receive', function($serv, $fd, $from_id, $data) {//把收到的数据 提交到异步回调中$task_id = $serv->task($data);});$serv->on('task', function ($serv, $task_id, $from_id, $data) {//接受数据,发送邮箱信息$data = json_decode($data,true);if(isset($data['email'])){(new SmtpMail())->send($data['email'],$data['code'],$data['msg']);}$serv->finish('');});$serv->on('finish', function ($serv, $task_id, $data) {});$serv->start();}}
SmtpMail类
namespace app\common\service;use app\common\model\SystemLog;use PHPMailer\PHPMailer\PHPMailer;use think\Exception;use think\Log;class SmtpMail{private $host;private $port = 25;private $user;private $pass;private $sock;private $mail_format = 0;public function __construct(){}public function send($email,$code,$msg){$mail = new PHPMailer(true); // Passing `true` enables exceptionstry {//服务器配置$mail->CharSet ="UTF-8"; //设定邮件编码$mail->SMTPDebug = 0; // 调试模式输出$mail->isSMTP(); // 使用SMTP$mail->Host = 'smtp.163.com'; // SMTP服务器$mail->SMTPAuth = true; // 允许 SMTP 认证$mail->Username = 'xxx'; // SMTP 用户名 即邮箱的用户名$mail->Password = 'xxx'; // SMTP 密码 部分邮箱是授权码(例如163邮箱)$mail->setFrom('xxx@163.com', 'xxx'); //发件人$mail->addAddress($email, 'xxx'); // 收件人$mail->addReplyTo('xxx@163.com', 'xxx'); //回复的时候回复给哪个邮箱 建议和发件人一致//Content$mail->isHTML(true); // 是否以HTML文档格式发送 发送后客户端可直接显示对应HTML内容$mail->Subject = 'xxx';$mail->Body = $msg;$mail->AltBody = $msg;$res = $mail->send();return ['code'=>1,'msg'=>'发送成功'];} catch (Exception $e) {return ['code'=>0,'msg'=>$mail->ErrorInfo];}}//发送邮箱信息public function addSend($email,$code,$msg){$client = new \swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_SYNC);$ret = $client->connect("127.0.0.1", 8122);if(empty($ret)){return true;} else {$client->send(json_encode([ 'type'=>1,'email'=>$email,'code'=>$code,'msg'=> $msg]));}return true;}}
服务端运行
namespace app\index\controller;use app\common\service\EmailService;class server{public function email_server(){ (new EmailService())->email_server();}}
在终端运行命令 php index.php /index/server/email_server
发送测试
<?phpnamespace app\index\controller;use app\common\service\SmtpMail;use think\Controller;class Index extends Controller{public function index_send_mail(){(new SmtpMail())->addSend("邮箱地址",0,"内容");}}
来源地址:https://blog.csdn.net/qq_34605417/article/details/128845949