lasthourcloud/app/Notifications/Channels/EmailChannel.php

79 lines
2.8 KiB
PHP
Raw Normal View History

2023-06-01 10:15:33 +00:00
<?php
namespace App\Notifications\Channels;
2023-08-08 15:28:36 +00:00
use Exception;
2023-06-01 10:15:33 +00:00
use Illuminate\Mail\Message;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Mail;
class EmailChannel
{
public function send(SendsEmail $notifiable, Notification $notification): void
{
try {
$this->bootConfigs($notifiable);
2024-01-07 22:32:54 +00:00
$recipients = $notifiable->getRecepients($notification);
if (count($recipients) === 0) {
throw new Exception('No email recipients found');
}
2023-06-12 10:00:01 +00:00
$mailMessage = $notification->toMail($notifiable);
Mail::send(
[],
[],
fn (Message $message) => $message
2024-01-07 22:32:54 +00:00
->to($recipients)
->subject($mailMessage->subject)
2024-06-10 20:43:34 +00:00
->html((string) $mailMessage->render())
);
} catch (Exception $e) {
$error = $e->getMessage();
if ($error === 'No email settings found.') {
throw $e;
}
ray($e->getMessage());
2023-10-18 12:22:09 +00:00
$message = "EmailChannel error: {$e->getMessage()}. Failed to send email to:";
2024-01-07 22:32:54 +00:00
if (isset($recipients)) {
$message .= implode(', ', $recipients);
2023-10-18 12:22:09 +00:00
}
2023-11-06 09:23:51 +00:00
if (isset($mailMessage)) {
$message .= " with subject: {$mailMessage->subject}";
}
2023-10-18 12:22:09 +00:00
send_internal_notification($message);
throw $e;
2023-06-01 10:15:33 +00:00
}
}
private function bootConfigs($notifiable): void
{
2023-08-31 13:00:59 +00:00
if (data_get($notifiable, 'use_instance_email_settings')) {
$type = set_transanctional_email_settings();
2024-06-10 20:43:34 +00:00
if (! $type) {
2023-08-31 13:00:59 +00:00
throw new Exception('No email settings found.');
}
2024-06-10 20:43:34 +00:00
2023-08-31 13:00:59 +00:00
return;
}
2023-11-06 09:26:56 +00:00
config()->set('mail.from.address', data_get($notifiable, 'smtp_from_address', 'test@example.com'));
config()->set('mail.from.name', data_get($notifiable, 'smtp_from_name', 'Test'));
2023-08-31 13:00:59 +00:00
if (data_get($notifiable, 'resend_enabled')) {
config()->set('mail.default', 'resend');
config()->set('resend.api_key', data_get($notifiable, 'resend_api_key'));
}
if (data_get($notifiable, 'smtp_enabled')) {
2023-08-21 09:11:51 +00:00
config()->set('mail.default', 'smtp');
config()->set('mail.mailers.smtp', [
2024-06-10 20:43:34 +00:00
'transport' => 'smtp',
'host' => data_get($notifiable, 'smtp_host'),
'port' => data_get($notifiable, 'smtp_port'),
'encryption' => data_get($notifiable, 'smtp_encryption'),
'username' => data_get($notifiable, 'smtp_username'),
'password' => data_get($notifiable, 'smtp_password'),
'timeout' => data_get($notifiable, 'smtp_timeout'),
'local_domain' => null,
2023-08-21 09:11:51 +00:00
]);
}
2023-06-01 10:15:33 +00:00
}
}