mailFactory = $mailFactory ?? app(MailFactory::class);
}
public function forTenant(string $tenantCode): self
{
parent::forTenant($tenantCode);
if ($this->clientIntegration) {
$this->mailer = $this->resolveMailer();
$this->usesClientMailer = true;
} else {
$this->mailer = $this->mailFactory->mailer();
$this->usesClientMailer = false;
}
return $this;
}
public function forClient(Client|string $client): self
{
parent::forClient($client);
$this->tenant = $this->clientContext?->tenants()->first();
if ($this->clientIntegration) {
$this->mailer = $this->resolveMailer();
$this->usesClientMailer = true;
} else {
$this->mailer = $this->mailFactory->mailer();
$this->usesClientMailer = false;
}
return $this;
}
public function getHeaders(): array
{
return [];
}
public function send(string|array $recipient, string $subject, string $content): void
{
if (! $this->mailer || ! $this->tenant) {
throw new Exception('MailService no está configurado. Llamá a forTenant() o forClient() primero.');
}
$this->tenant->loadMissing(['headerLogo', 'footerLogo']);
$html = Blade::render(
<<<'BLADE'
La integración SMTP de '.e($this->clientContext->name).' fue configurada correctamente.
' .'Este mensaje fue enviado automáticamente para validar las credenciales de correo.
'; if ($this->tenant) { $this->send($recipient, $subject, $content); return; } $this->mailer->to($recipient)->send( (new Mailable)->subject($subject)->html($content) ); } private function resolveMailer(): Mailer { $data = $this->clientIntegration?->integration_data; if (! is_array($data)) { throw new InvalidArgumentException('La configuración SMTP del cliente no es válida.'); } foreach (self::REQUIRED_SMTP_FIELDS as $field) { if (! array_key_exists($field, $data) || $data[$field] === null || $data[$field] === '') { throw new InvalidArgumentException("Falta {$field} en la configuración SMTP del cliente."); } } // MailFake implements MailFactory but cannot build transports. if (! $this->mailFactory instanceof MailManager) { return $this->mailFactory->mailer(); } $mailer = $this->mailFactory->build([ 'name' => 'client-smtp-'.$this->clientContext?->id, 'transport' => 'smtp', 'scheme' => $data['MAIL_SCHEME'] ?? null, 'host' => $data['MAIL_HOST'], 'port' => (int) $data['MAIL_PORT'], 'username' => $data['MAIL_USERNAME'], 'password' => $data['MAIL_PASSWORD'], 'timeout' => isset($data['MAIL_TIMEOUT']) ? (int) $data['MAIL_TIMEOUT'] : null, 'local_domain' => $data['MAIL_EHLO_DOMAIN'] ?? null, ]); $mailer->alwaysFrom( $data['MAIL_FROM_ADDRESS'], $data['MAIL_FROM_NAME'] ?? $this->clientContext?->name, ); return $mailer; } }