Files
safekat/ci4/app/Services/EmailService.php
2025-05-21 21:25:02 +02:00

62 lines
2.3 KiB
PHP
Executable File

<?php
namespace App\Services;
use Config\Services;
class EmailService
{
public function send(string $subject, string $body, $recipient): bool
{
$skEnv = env('SK_ENVIRONMENT', 'production'); // fallback a producción si no está definido
// Si no estamos en producción, forzar el destinatario a uno fijo
if ($skEnv !== 'production') {
$recipient = env('MAIL_DEV_RECIPIENT', 'imnavajas@coit.es,info@jjimenez.eu'); // fallback opcional
}
$settings_model = model('App\Models\Configuracion\ConfigVariableModel');
$gateway = $settings_model->getVariable('email_protocol')->value;
$body = html_entity_decode($body);
if ($gateway === 'smtp') {
try {
$email = Services::email();
$emailConfig = [
'protocol' => $gateway,
'SMTPHost' => $settings_model->getVariable('email_host')->value,
'SMTPUser' => $settings_model->getVariable('email_from_address')->value,
'SMTPPass' => $settings_model->getVariable('email_pass')->value,
'SMTPPort' => (int) $settings_model->getVariable('email_port')->value,
'SMTPCrypto' => $settings_model->getVariable('email_cert')->value === 'none' ? '' : $settings_model->getVariable('email_cert')->value,
'SMTPTimeout' => 15,
'mailType' => 'html',
'wordWrap' => true,
];
$email->initialize($emailConfig);
$email->setFrom($settings_model->getVariable('email_from_address')->value, $settings_model->getVariable('email_from_name')->value);
$email->setTo($recipient);
$email->setSubject($subject);
$email->setMessage($body);
if (!$email->send()) {
log_message('error', 'Error enviando email: ' . $email->printDebugger(['headers', 'subject', 'body']));
return false;
}
return true;
} catch (\Throwable $e) {
log_message('error', 'EmailService failed: ' . $e->getMessage());
return false;
}
}
return false;
}
}