false, 'message' => "Environment file not found" ]); exit; } try { $envDir = dirname($envFile); $dotenv = Dotenv::createImmutable($envDir, '.env.mail'); $dotenv->load(); } catch (Throwable $e) { http_response_code(500); echo json_encode([ 'success' => false, 'message' => "Dotenv error" ]); } function newMailer() { global $mailer; if (isset($mailer) && $mailer instanceof PHPMailer) { return; } try { $mailer = new PHPMailer(true); $mailer->isSMTP(); $mailer->CharSet = 'UTF-8'; $mailer->Host = $_ENV['MAIL_SERVER']; $mailer->SMTPAuth = true; $mailer->Username = $_ENV['MAIL_USER']; $mailer->Password = $_ENV['MAIL_USER_PASSWORD']; $port = (int)$_ENV['MAIL_PORT']; if ($port === 465) { $mailer->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; } else { $mailer->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; $mailer->Port = 587; } $mailer->Port = $port; $mailer->setFrom($_ENV['MAIL_USER'], 'WKVS'); } catch (Exception $e) { throw new Exception("Konfigurationsfehler des Automailers: " . $e->getMessage()); } } function sendMail(string $content = '', string $subject = '', array $recipients = []) { global $mailer; if (empty($recipients)) { throw new Exception("Keine Empfänger angegeben"); } if (!isset($mailer) || !($mailer instanceof PHPMailer)) { try { newMailer(); } catch (Exception $e) { throw $e; } } try { foreach ($recipients as $email => $name) { $mailer->addAddress($email, $name); } $mailer->isHTML(true); $mailer->Subject = $subject; $mailer->Body = $content; $mailer->AltBody = strip_tags($content); if (!$mailer->send()) { throw new Exception("Sendefehler " . $mailer->ErrorInfo); } return true; } catch (Exception $e) { error_log("Kritischer Sendefehler: " . $e->getMessage()); throw $e; } } ?>