YogaSoul

$message

HTML; } // Trasforma il testo del modulo in HTML: // **testo** -> grassetto, link cliccabili, a capo ->
function formatEmailBody(string $text): string { $html = htmlspecialchars($text, ENT_QUOTES, 'UTF-8'); $html = preg_replace('/\*\*([^*\n]+?)\*\*/', '$1', $html); $html = preg_replace('~(https?://[^\s<]+)~', '$1', $html); return nl2br($html); } // Gestione della richiesta try { if ($_SERVER['REQUEST_METHOD'] !== 'POST') { throw new Exception('Metodo non consentito.'); } $subject = isset($_POST['subject']) ? trim($_POST['subject']) : ''; $body = isset($_POST['body']) ? trim($_POST['body']) : ''; $recipients = isset($_POST['recipients']) ? json_decode($_POST['recipients'], true) : []; if (empty($subject) || empty($body) || empty($recipients) || !is_array($recipients)) { throw new Exception('Dati mancanti.'); } // Invii multipli: più tempo a disposizione dello script @set_time_limit(300); // Configura PHPMailer $mail = new PHPMailer(true); $mail->isSMTP(); $mail->Host = $_ENV['MAIL_HOST']; $mail->SMTPAuth = true; $mail->Username = $_ENV['MAIL_USERNAME']; $mail->Password = $_ENV['MAIL_PASSWORD']; $mail->SMTPSecure = $_ENV['MAIL_ENCRYPTION']; $mail->Port = (int) $_ENV['MAIL_PORT']; $mail->Timeout = 5; $mail->SMTPKeepAlive = true; // una sola connessione per tutti gli invii $mail->CharSet = 'UTF-8'; // accenti ed emoji corretti $mail->setFrom($_ENV['MAIL_FROM_ADDRESS'], $_ENV['MAIL_FROM_NAME']); $mail->isHTML(true); $mail->Subject = $subject; $sent = 0; $failed = []; // Un'email per ogni destinatario: nessuno vede gli indirizzi degli altri foreach ($recipients as $r) { $email = trim($r['email'] ?? ''); if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $failed[] = $email !== '' ? $email : '(email vuota)'; continue; } $nome = trim((string) ($r['nome'] ?? '')); if ($nome === '') { $nome = 'allieva/o'; } $personalText = str_replace('{nome}', $nome, $body); try { $mail->clearAddresses(); $mail->addAddress($email, $nome); $mail->Body = generateEmailTemplate(formatEmailBody($personalText)); $mail->AltBody = str_replace('**', '', $personalText); $mail->send(); $sent++; } catch (Exception $e) { $failed[] = $email; error_log('Errore invio a ' . $email . ': ' . $mail->ErrorInfo); $mail->getSMTPInstance()->reset(); } } $mail->smtpClose(); if ($sent === 0) { throw new Exception('Nessuna email inviata.'); } $message = 'Email inviate: ' . $sent; if (!empty($failed)) { $message .= '. Non inviate (' . count($failed) . '): ' . implode(', ', $failed); } echo json_encode(['success' => true, 'message' => $message, 'sent' => $sent, 'failed' => $failed]); } catch (\Throwable $e) { error_log('Errore in send_email.php: ' . $e->getMessage() . ' in ' . $e->getFile() . ' at line ' . $e->getLine()); echo json_encode(['success' => false, 'message' => "Errore nell'invio dell'email: " . $e->getMessage()]); }