<?php
session_start();
require_once "PHPMailer/src/Exception.php";
require_once "PHPMailer/src/PHPMailer.php";
require_once "PHPMailer/src/SMTP.php";
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
// Grundeinstellungen
$recipient_email = "mail.deinedomain.de";
$sender_name = "Kontaktformular";
$success_message = "Vielen Dank für Ihre Nachricht!";
// SMTP-Konfiguration - Nur ausfüllen wenn Sie SMTP verwenden möchten
/*
$smtp_host = "smtp.gmail.com";
$smtp_port = 587;
$smtp_secure = "tls";
$smtp_user = "
ihre.email@gmail.com";
$smtp_pass = "ihr_app_passwort";
$smtp_from_name = "Ihr Name";
*/
// Automatische Antwort-Einstellungen
$enable_auto_reply = true;
$auto_reply_subject = "Ihre Nachricht wurde erhalten";
$auto_reply_message = "Hallo,
vielen Dank für Ihre Nachricht. Wir haben Ihre Anfrage erhalten und werden uns schnellstmöglich bei Ihnen melden.
Mit freundlichen Grüßen
Ihr Team";
$auto_reply_include_original = true;
$auto_reply_html_format = false;
$auto_reply_sender_name = "Support-Team";
// Datei-Upload-Einstellungen
$allowed_extensions = ["jpg", "png", "pdf", "doc", "docx"];
$max_filesize_mb = 5;
$uploads_dir = "uploads/";
function sanitize_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data, ENT_QUOTES, "UTF-8");
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Anti-Spam Überprüfungen
if (!isset($_POST["csrf_token"]) || $_POST["csrf_token"] !== ($_SESSION["csrf_token"] ?? null)) {
http_response_code(400);
echo json_encode(["success" => false, "message" => "Sicherheitsfehler: Ungültiges Token."]);
exit;
}
if (!empty($_POST["name_hp"])) {
http_response_code(400);
echo json_encode(["success" => false, "message" => "Honeypot-Feld ausgefüllt, dies ist ein Spam-Versuch."]);
exit;
}
$time_diff = time() - ($_SESSION["form_start_time"] ?? 0);
if ($time_diff < 3) {
http_response_code(400);
echo json_encode(["success" => false, "message" => "Formular zu schnell ausgefüllt."]);
exit;
}
// Validierung der Pflichtfelder
$required_fields = ["name", "email", "subject", "message"];
$errors = [];
foreach ($required_fields as $field_name) {
if (!empty($field_name) && (empty($_POST[$field_name]) && empty($_FILES[$field_name]["tmp_name"]))) {
$errors[] = $field_name;
}
}
// CAPTCHA-Überprüfung
if (!isset($_POST["captcha"]) || intval($_POST["captcha"]) !== ($_SESSION["captcha_sum"] ?? null)) {
$errors[] = "captcha";
}
if (!empty($errors)) {
http_response_code(400);
echo json_encode(["success" => false, "message" => "Bitte füllen Sie alle Pflichtfelder aus.", "errors" => $errors]);
exit;
}
// Absender-E-Mail ermitteln
$sender_email = "";
foreach ($_POST as $key => $value) {
if (strpos(strtolower($key), "email") !== false || strpos(strtolower($key), "mail") !== false) {
$sanitized_value = filter_var(sanitize_input($value), FILTER_SANITIZE_EMAIL);
if (filter_var($sanitized_value, FILTER_VALIDATE_EMAIL)) {
$sender_email = $sanitized_value;
break;
}
}
}
// E-Mail-Betreff erstellen
$subject = "Neue Nachricht aus dem Formular";
if (!empty($_POST)) {
$skip_keys = ["csrf_token", "name_hp", "captcha"];
$visible_values = [];
foreach ($_POST as $key => $value) {
if (in_array($key, $skip_keys, true)) continue;
if (is_array($value)) continue;
if (trim((string)$value) === "") continue;
$visible_values[] = $value;
}
$first_value = $visible_values[0] ?? reset($_POST);
if (!empty($first_value)) {
$subject = "Nachricht von " . sanitize_input($first_value);
}
}
// E-Mail-Inhalt erstellen
$mail_content_html = "<div style=\"font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;\">
<h2 style=\"color: #333; border-bottom: 2px solid #007bff; padding-bottom: 10px;\">
Neue Nachricht aus dem Formular
</h2>
<p>Hallo,</p>
<p>Sie haben eine neue Nachricht aus dem Kontaktformular erhalten:</p>
<table style=\"border-collapse: collapse; width: 100%; border: 1px solid #ddd; margin: 20px 0;\">
<tbody>";
$mail_content_text = "Neue Nachricht aus dem Formular:\n\n";
foreach ($_POST as $key => $value) {
if ($key === "captcha" || $key === "csrf_token" || $key === "name_hp") continue;
$label = ucfirst(str_replace(["_", "-"], " ", $key));
if (is_array($value)) {
$value_str = implode(", ", array_map("htmlspecialchars", $value));
$value_text = implode(", ", $value);
} else {
$value_str = sanitize_input($value);
$value_text = $value;
}
$mail_content_html .= "<tr>
<td style=\"padding: 12px; border: 1px solid #ddd; background-color: #f8f9fa; width: 30%; font-weight: bold; vertical-align: top;\">" . $label . "</td>
<td style=\"padding: 12px; border: 1px solid #ddd; vertical-align: top;\">" . nl2br($value_str) . "</td>
</tr>";
$mail_content_text .= $label . ": " . $value_text . "\n";
}
$mail_content_html .= "</tbody></table></div>";
// Dateiuploads verarbeiten
$uploaded_files = [];
if (!empty($_FILES)) {
foreach ($_FILES as $field_name => $file) {
if ($file["error"] === UPLOAD_ERR_OK) {
$file_name = sanitize_input(basename($file["name"]));
$file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
if (!in_array($file_ext, $allowed_extensions)) {
http_response_code(400);
echo json_encode(["success" => false, "message" => "Fehler: Dateityp " . htmlspecialchars($file_ext) . " nicht erlaubt."]);
exit;
}
if ($file["size"] > $max_filesize_mb * 1024 * 1024) {
http_response_code(400);
echo json_encode(["success" => false, "message" => "Fehler: Maximale Dateigröße von " . $max_filesize_mb . "MB überschritten."]);
exit;
}
$unique_file_name = uniqid() . "-" . $file_name;
$target_file = $uploads_dir . $unique_file_name;
if (move_uploaded_file($file["tmp_name"], $target_file)) {
$uploaded_files[] = [
"name" => $file_name,
"path" => $target_file,
"size" => $file["size"]
];
} else {
http_response_code(500);
echo json_encode(["success" => false, "message" => "Fehler beim Hochladen der Datei."]);
exit;
}
$mail_content_html .= "<p style=\"margin-top: 20px;\"><strong>Anhang:</strong> " . htmlspecialchars($file_name) . " (" . number_format($file["size"] / 1024, 1) . " KB)</p>";
$mail_content_text .= "\nAnhang: " . htmlspecialchars($file_name) . " (" . number_format($file["size"] / 1024, 1) . " KB)\n";
}
}
}
// E-MAIL VERSENDEN - KORRIGIERTE VERSION
$main_mail_sent = false;
try {
$mail = new PHPMailer(true);
// SMTP-Konfigurationsprüfung
$use_smtp = isset($smtp_host) && isset($smtp_user) && isset($smtp_pass) &&
!empty($smtp_host) && !empty($smtp_user) && !empty($smtp_pass);
if ($use_smtp) {
$mail->isSMTP();
$mail->Host = $smtp_host;
$mail->SMTPAuth = true;
$mail->Username = $smtp_user;
$mail->Password = $smtp_pass;
$mail->Timeout = 60;
$mail->SMTPKeepAlive = false;
if (isset($smtp_secure) && strtolower($smtp_secure) === "ssl") {
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
$mail->Port = isset($smtp_port) ? (int)$smtp_port : 465;
} else {
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = isset($smtp_port) ? (int)$smtp_port : 587;
}
$from_email = filter_var($smtp_user, FILTER_VALIDATE_EMAIL);
if (!$from_email) {
throw new Exception("Ungültige SMTP-Benutzer-E-Mail-Adresse: " . $smtp_user);
}
$mail->setFrom($from_email, isset($smtp_from_name) ? $smtp_from_name : $sender_name);
} else {
$mail->isMail();
$validated_recipient = filter_var($recipient_email, FILTER_VALIDATE_EMAIL);
if (!$validated_recipient) {
throw new Exception("Ungültige Empfänger-E-Mail-Adresse");
}
$mail->setFrom($validated_recipient, $sender_name);
}
$validated_recipient = filter_var($recipient_email, FILTER_VALIDATE_EMAIL);
if (!$validated_recipient) {
throw new Exception("Ungültige Empfänger-E-Mail-Adresse: " . $recipient_email);
}
$mail->addAddress($validated_recipient);
if ($sender_email && filter_var($sender_email, FILTER_VALIDATE_EMAIL)) {
$mail->addReplyTo($sender_email);
}
foreach ($uploaded_files as $file) {
if (file_exists($file["path"])) {
$mail->addAttachment($file["path"], $file["name"]);
}
}
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $mail_content_html;
$mail->AltBody = strip_tags($mail_content_text);
$mail->CharSet = "UTF-8";
$mail->Encoding = "base64";
$mail->send();
$main_mail_sent = true;
} catch (Exception $e) {
error_log("Mail Error: " . $e->getMessage());
$error_message = "Fehler beim Senden der E-Mail.";
if (strpos($e->getMessage(), "SMTP connect()") !== false) {
$error_message = "SMTP-Verbindung fehlgeschlagen. Prüfen Sie Host und Port.";
} elseif (strpos($e->getMessage(), "SMTP Error: Could not authenticate") !== false) {
$error_message = "SMTP-Authentifizierung fehlgeschlagen. Prüfen Sie Benutzername und Passwort.";
} elseif (strpos($e->getMessage(), "mailbox unavailable") !== false) {
$error_message = "E-Mail-Adresse ungültig oder Mailbox nicht verfügbar.";
} elseif (strpos($e->getMessage(), "Invalid address") !== false) {
$error_message = "Ungültige E-Mail-Adresse erkannt.";
}
http_response_code(500);
echo json_encode([
"success" => false,
"message" => $error_message,
"debug" => "Technische Details wurden protokolliert."
]);
exit;
}
// AUTOMATISCHE ANTWORT
if ($main_mail_sent && $enable_auto_reply && !empty($sender_email)) {
$validated_sender = filter_var($sender_email, FILTER_VALIDATE_EMAIL);
if ($validated_sender) {
$auto_reply_body_text = $auto_reply_message;
$auto_reply_body_html = nl2br(htmlspecialchars($auto_reply_message));
if ($auto_reply_include_original) {
$original_message = "\n\n" . str_repeat("-", 50) . "\nIhre ursprüngliche Nachricht:\n\n";
$original_html = "<hr style=\"margin: 30px 0;\"><h3>Ihre ursprüngliche Nachricht:</h3>";
foreach ($_POST as $key => $value) {
if ($key === "captcha" || $key === "csrf_token" || $key === "name_hp") continue;
$label = ucfirst(str_replace(["_", "-"], " ", $key));
$value_display = is_array($value) ? implode(", ", $value) : $value;
$original_message .= $label . ": " . $value_display . "\n";
$original_html .= "<p><strong>" . htmlspecialchars($label) . ":</strong> " . htmlspecialchars($value_display) . "</p>";
}
$auto_reply_body_text .= $original_message;
$auto_reply_body_html .= $original_html;
}
try {
$auto_mail = new PHPMailer(true);
if ($use_smtp) {
$auto_mail->isSMTP();
$auto_mail->Host = $smtp_host;
$auto_mail->SMTPAuth = true;
$auto_mail->Username = $smtp_user;
$auto_mail->Password = $smtp_pass;
$auto_mail->Timeout = 60;
if (isset($smtp_secure) && strtolower($smtp_secure) === "ssl") {
$auto_mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
$auto_mail->Port = isset($smtp_port) ? (int)$smtp_port : 465;
} else {
$auto_mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$auto_mail->Port = isset($smtp_port) ? (int)$smtp_port : 587;
}
$auto_mail->setFrom($smtp_user, $auto_reply_sender_name);
} else {
$auto_mail->isMail();
$auto_mail->setFrom($validated_recipient, $auto_reply_sender_name);
}
$auto_mail->addAddress($validated_sender);
$auto_mail->isHTML($auto_reply_html_format);
$auto_mail->Subject = $auto_reply_subject;
$auto_mail->Body = $auto_reply_body_html;
$auto_mail->AltBody = strip_tags($auto_reply_body_text);
$auto_mail->CharSet = "UTF-8";
$auto_mail->Encoding = "base64";
$auto_mail->send();
} catch (Exception $e) {
error_log("Auto-Reply Error: " . $e->getMessage());
}
}
}
// CAPTCHA-Session löschen
unset($_SESSION["captcha_sum"]);
echo json_encode(["success" => true, "message" => $success_message]);
exit;
} else {
http_response_code(403);
echo json_encode(["success" => false, "message" => "Direkter Zugriff nicht erlaubt."]);
exit;
}
?>