Files
hdk-core/src/Service/EmailService.php
2024-09-12 19:06:23 +08:00

141 lines
3.4 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 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;
/**
* 邮箱验证码
*/
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')
);
}
public static function make(
?string $dsn = null,
?string $mailSenderName = null,
?string $mailSender = null
): EmailService {
return new static(
$dsn,
$mailSenderName,
$mailSender,
);
}
/**
* 发送邮件
*
* @param string $target
* @param string $subject
* @param string $text
*
* @return bool
* @throws TransportExceptionInterface
* @see EmailService::sendText
* @see EmailService::sendHtml
* @deprecated
* @noinspection PhpUnused
*/
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
* @param array $bcc
*
* @return bool
* @throws TransportExceptionInterface
*/
public function sendText(
$target,
string $subject,
string $text,
array $cc = [],
array $bcc = []
): bool {
$email = (new Email())
->from(Address::create($this->from))
->to(...(is_array($target) ? $target : [$target]))
->cc(...$cc)
->bcc(...$bcc)
->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 array $bcc
*
* @return bool
* @throws TransportExceptionInterface
*/
public function sendHtml(
$target,
string $subject,
string $html,
array $cc = [],
array $bcc = []
): bool {
$email = (new Email())
->from(Address::create($this->from))
->to(...(is_array($target) ? $target : [$target]))
->cc(...$cc)
->bcc(...$bcc)
->subject($subject)
->html($html);
$this->mailer->send($email);
return true;
}
}