server/app/Service/Message/Channel/EmailChannel.php

56 lines
1.6 KiB
PHP

<?php
namespace App\Service\Message\Channel;
use App\Model\Account;
use App\Model\Message;
use App\Service\Message\Exception\ChannelFailException;
use App\Service\Message\Interface\ChannelInterface;
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mailer\Transport;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;
use function Hyperf\Config\config;
class EmailChannel implements ChannelInterface
{
protected Mailer $mailer;
public function __construct()
{
$config = config('mailer.default');
// 创建传输器
$transport = Transport::fromDsn(sprintf(
'smtp://%s:%s@%s:%d?encryption=%s',
$config['username'],
$config['password'],
$config['host'],
$config['port'],
$config['encryption']
));
$this->mailer = new Mailer($transport);
}
public function send(Account $account, Message $message): bool
{
try {
if (!$account->email) {
throw new ChannelFailException("用户邮箱地址不存在");
}
$email = (new Email())
->from(new Address(config("mailer.default.username"), config("mailer.default.name")))
->to($account->email)
->subject($message->title)
->html($message->content);
$this->mailer->send($email);
return true;
} catch (\Exception $exception) {
throw new ChannelFailException($exception->getMessage());
}
}
public function getName(): string
{
return "email";
}
}