hyperf-chat/app/Service/MailerService.php

86 lines
4.8 KiB
PHP
Raw Normal View History

2021-02-04 23:36:14 +08:00
<?php
2021-09-04 20:18:20 +08:00
declare(strict_types=1);
2021-02-04 23:36:14 +08:00
namespace App\Service;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
/**
* Class MailerService
2021-04-20 16:30:57 +08:00
*
2021-02-04 23:36:14 +08:00
* @package App\Service
*/
class MailerService
{
/**
* 消息队列
*
* @var bool
*/
public $queueSwitch = false;
/**
* 发送邮件
*
2021-04-20 16:30:57 +08:00
* @param string $email 邮箱
* @param string $subject 标题
2021-02-04 23:36:14 +08:00
* @param string $template 对应邮件模板
* @return bool
*/
2021-09-04 20:18:20 +08:00
public function send(string $email, string $subject, string $template): bool
2021-02-04 23:36:14 +08:00
{
if ($this->queueSwitch) {
}
return $this->realSend($email, $subject, $template);
}
/**
* 发送邮件
*
2021-04-20 16:30:57 +08:00
* @param string $email 邮箱
* @param string $subject 标题
2021-02-04 23:36:14 +08:00
* @param string $template 对应邮件模板
* @return bool
*/
2021-09-04 20:18:20 +08:00
public function realSend(string $email, string $subject, string $template): bool
2021-02-04 23:36:14 +08:00
{
try {
return $this->mail($email, $subject, $template);
} catch (Exception $e) {
return false;
}
}
/**
* 推送邮件
*
* @param string $address 收件人
* @param string $subject 邮件标题
2021-04-20 16:30:57 +08:00
* @param string $view 邮件内容
2021-02-04 23:36:14 +08:00
* @return bool
* @throws Exception
*/
private function mail(string $address, string $subject, string $view): bool
{
$config = config('mail');
$mail = new PHPMailer();
$mail->CharSet = 'UTF-8';
2021-09-04 20:18:20 +08:00
$mail->IsSMTP(); // 设定使用SMTP服务
$mail->SMTPDebug = 0; // 关闭SMTP调试功能
$mail->SMTPAuth = true; // 启用 SMTP 验证功能
$mail->SMTPSecure = 'ssl'; // 使用安全协议
2021-02-04 23:36:14 +08:00
$mail->Host = $config['host'];
$mail->Port = $config['port'];
$mail->Username = $config['username'];
$mail->Password = $config['password'];
$mail->SetFrom($config['from'], $config['name']);
$mail->Subject = $subject;
$mail->MsgHTML($view);
$mail->AddAddress($address); // 收件人
return $mail->Send();
}
}