Steuerkram/src/Services/EmailService.php

81 lines
2.8 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
declare(strict_types=1);
namespace Steuerkram\Services;
class EmailService
{
/**
* Sendet eine Rechnung als PDF-Anhang an alle Empfänger.
*
* @param string[] $recipients E-Mail-Adressen (1–3)
* @throws \RuntimeException
*/
public function sendInvoice(array $invoice, array $lines, array $settings, array $recipients): void
{
$mailer = $this->buildMailer($settings);
$pdfService = new PdfInvoiceService();
$pdfContent = $pdfService->renderToString($invoice, $lines, $settings);
$nr = $invoice['rechnungs_nr'] ?? 'Entwurf';
$filename = 'Rechnung-' . $nr . '.pdf';
$defaultBody = "Guten Tag,\n\n"
. "anbei erhalten Sie die Rechnung %RNR% von %FNAME%.\n\n"
. "Bei Fragen stehen wir Ihnen gerne zur Verfügung.\n\n"
. "Mit freundlichen Grüßen\n"
. "%INHABER%";
$subjectTpl = ($settings['mail_subject_template'] ?? '') ?: 'Rechnung %RNR%';
$bodyTpl = ($settings['mail_body_template'] ?? '') ?: $defaultBody;
$subject = $this->replacePlaceholders($subjectTpl, $invoice, $settings);
$body = $this->replacePlaceholders($bodyTpl, $invoice, $settings);
$mailer->send($recipients, $subject, $body, $pdfContent, $filename);
}
/**
* Sendet eine Test-Mail an die angegebene Adresse.
*
* @throws \RuntimeException
*/
public function sendTestMail(array $settings, string $to): void
{
$mailer = $this->buildMailer($settings);
$mailer->send(
[$to],
'Steuerkram – SMTP-Test',
"Die SMTP-Konfiguration funktioniert korrekt.\n\nDiese Mail wurde von Steuerkram gesendet."
);
}
private function replacePlaceholders(string $text, array $invoice, array $settings): string
{
return str_replace(
['%RNR%', '%FNAME%', '%INHABER%'],
[$invoice['rechnungs_nr'] ?? 'Entwurf', $settings['firma'] ?? '', $settings['inhaber'] ?? ''],
$text
);
}
private function buildMailer(array $settings): SmtpMailer
{
$host = $settings['mail_smtp_host'] ?? '';
if (empty($host)) {
throw new \RuntimeException('SMTP-Host ist nicht konfiguriert.');
}
return new SmtpMailer(
host: $host,
port: (int)($settings['mail_smtp_port'] ?? 587),
encryption: $settings['mail_smtp_encryption'] ?? 'tls',
user: $settings['mail_smtp_user'] ?? '',
pass: $settings['mail_smtp_pass'] ?? '',
fromEmail: $settings['mail_from_email'] ?: ($settings['email'] ?? ''),
fromName: $settings['mail_from_name'] ?: ($settings['firma'] ?? ''),
);
}
}