70 lines
1.7 KiB
PHP
Executable File
70 lines
1.7 KiB
PHP
Executable File
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use Illuminate\Support\Facades\Mail;
|
|
use Illuminate\Support\Facades\Log;
|
|
|
|
class EmailService
|
|
{
|
|
protected array $from = [];
|
|
protected array $to = [];
|
|
protected string $subject = '';
|
|
protected string $message = '';
|
|
|
|
public function setFrom(string $email, string $name = ''): self
|
|
{
|
|
$this->from = ['email' => $email, 'name' => $name];
|
|
return $this;
|
|
}
|
|
|
|
public function setTo(string|array $email): self
|
|
{
|
|
$this->to = is_array($email) ? $email : [$email];
|
|
return $this;
|
|
}
|
|
|
|
public function setSubject(string $subject): self
|
|
{
|
|
$this->subject = $subject;
|
|
return $this;
|
|
}
|
|
|
|
public function setMessage(string $message): self
|
|
{
|
|
$this->message = $message;
|
|
return $this;
|
|
}
|
|
|
|
public function send(string $to = '', string $subject = '', string $message = '', ?string $template = null): bool
|
|
{
|
|
if (!empty($to)) {
|
|
$this->setTo($to);
|
|
}
|
|
if ($subject !== '') {
|
|
$this->setSubject($subject);
|
|
}
|
|
if ($message !== '') {
|
|
$this->setMessage($message);
|
|
}
|
|
|
|
if (empty($this->to)) {
|
|
return false;
|
|
}
|
|
|
|
try {
|
|
Mail::html($this->message, function ($mail) use ($template) {
|
|
$mail->to($this->to);
|
|
if (!empty($this->from)) {
|
|
$mail->from($this->from['email'], $this->from['name']);
|
|
}
|
|
$mail->subject($this->subject);
|
|
});
|
|
return true;
|
|
} catch (\Throwable $e) {
|
|
Log::error('EmailService send failed: ' . $e->getMessage());
|
|
return false;
|
|
}
|
|
}
|
|
}
|