Files
hdk-core/src/Service/EmailService.php
2023-10-08 15:43:47 +08:00

129 lines
3.1 KiB
PHP

<?php
declare(strict_types=1);
/**
* This file is part of LuxAccountX.
*
* @link http://124.126.16.154:8888/WebService/LuxAccountX
* @document https://lux-software.yuque.com/htnx76/vcm2oc
* @contact dongyun.li@luxcreo.ai
*/
namespace Singularity\HDK\Core\Service;
use JetBrains\PhpStorm\Deprecated;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
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 EmailService
{
private Mailer $mailer;
private string $from;
public function __construct(
?string $dsn = null,
?string $mailSenderName = null,
?string $mailSender = null
) {
$dsn ??= config('common.third_party.email.dsn');
$transport = Transport::fromDsn($dsn);
$this->mailer = new Mailer($transport);
$this->from = sprintf(
"%s <%s>",
$mailSenderName ?? config('common.third_party.email.mailer_sender_name'),
$mailSender ?? config('common.third_party.email.mailer_sender')
);
}
/**
* 发送邮件
*
* @param string $target
* @param string $subject
* @param string $text
*
* @return bool
* @throws TransportExceptionInterface
* @see EmailService::sendText
* @see EmailService::sendHtml
*/
#[Deprecated]
public function sendCode(
string $target,
string $subject,
string $text
): bool {
return $this->sendText($target, $subject, $text);
}
/**
* @param string|array<string> $target
* @param string $subject
* @param string $text
* @param array<string> $cc
*
* @return bool
* @throws TransportExceptionInterface
*/
public function sendText(
string|array $target,
string $subject,
string $text,
array $cc = [],
int $priority = Email::PRIORITY_NORMAL
): bool {
$email = (new Email())
->from(Address::create($this->from))
->to(...(is_array($target) ? $target : [$target]))
->cc(...$cc)
->priority($priority)
->subject($subject)
->text($text);
$this->mailer->send($email);
return true;
}
/**
* 以 HTML 格式发送邮件
*
* @param string|array<string> $target
* @param string $subject
* @param string $html
* @param array<string> $cc
* @param int $priority
* @return bool
* @throws TransportExceptionInterface
*/
public function sendHtml(
string|array $target,
string $subject,
string $html,
array $cc = [],
int $priority = Email::PRIORITY_NORMAL
): bool {
$email = (new Email())
->from(Address::create($this->from))
->to(...(is_array($target) ? $target : [$target]))
->cc(...$cc)
->priority($priority)
->subject($subject)
->html($html);
$this->mailer->send($email);
return true;
}
}