email cert notifiche

This commit is contained in:
2026-10-05 15:13:05 +02:00
parent 86a6a413ed
commit b3e4f4051c
2 changed files with 231 additions and 854 deletions
+64 -34
View File
@@ -8,6 +8,7 @@ use PHPMailer\PHPMailer\Exception;
// Imposta l'header per JSON // Imposta l'header per JSON
header('Content-Type: application/json'); header('Content-Type: application/json');
ini_set('display_errors', '0'); // gli avvisi vanno nel log, non nella risposta
// Funzione per generare il template HTML dell'email // Funzione per generare il template HTML dell'email
function generateEmailTemplate($message) function generateEmailTemplate($message)
@@ -40,7 +41,7 @@ function generateEmailTemplate($message)
text-align: center; text-align: center;
} }
.header img { .header img {
max-width: 50px; /* Ridotto da 150px a 100px per rimpicciolire il logo */ max-width: 100px; /* Ridotto da 150px a 100px per rimpicciolire il logo */
} }
.content { .content {
padding: 30px; padding: 30px;
@@ -77,8 +78,8 @@ function generateEmailTemplate($message)
<div class="header"> <div class="header">
<img src="https://yogasoul.it/wp-content/uploads/2021/03/logotransizione_final2.png" <img src="https://yogasoul.it/wp-content/uploads/2021/03/logotransizione_final2.png"
alt="YogaSoul - My WordPress Blog" alt="YogaSoul - My WordPress Blog"
width="150" width="120"
style="display: block; width: 50px; height: auto;"> style="display: block; width: 120px; max-width: 120px; height: auto; margin: 0 auto;">
</div> </div>
<div class="content"> <div class="content">
@@ -95,6 +96,16 @@ function generateEmailTemplate($message)
HTML; HTML;
} }
// Trasforma il testo del modulo in HTML:
// **testo** -> grassetto, link cliccabili, a capo -> <br>
function formatEmailBody(string $text): string
{
$html = htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
$html = preg_replace('/\*\*([^*\n]+?)\*\*/', '<strong>$1</strong>', $html);
$html = preg_replace('~(https?://[^\s<]+)~', '<a href="$1">$1</a>', $html);
return nl2br($html);
}
// Gestione della richiesta // Gestione della richiesta
try { try {
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
@@ -105,26 +116,15 @@ try {
$body = isset($_POST['body']) ? trim($_POST['body']) : ''; $body = isset($_POST['body']) ? trim($_POST['body']) : '';
$recipients = isset($_POST['recipients']) ? json_decode($_POST['recipients'], true) : []; $recipients = isset($_POST['recipients']) ? json_decode($_POST['recipients'], true) : [];
if (empty($subject) || empty($body) || empty($recipients)) { if (empty($subject) || empty($body) || empty($recipients) || !is_array($recipients)) {
throw new Exception('Dati mancanti.'); throw new Exception('Dati mancanti.');
} }
// Prepara tutti gli indirizzi email ricevuti // Invii multipli: più tempo a disposizione dello script
$to = array_column($recipients, 'email'); @set_time_limit(300);
if (empty($to)) {
throw new Exception('Nessun destinatario valido trovato.');
}
// Sostituisci i newline con <br> per l'HTML
$htmlBody = nl2br($body);
$emailContent = generateEmailTemplate($htmlBody);
// Configura PHPMailer // Configura PHPMailer
$mail = new PHPMailer(true); $mail = new PHPMailer(true);
// Configurazione server SMTP con dati da .env
$mail->isSMTP(); $mail->isSMTP();
$mail->Host = $_ENV['MAIL_HOST']; $mail->Host = $_ENV['MAIL_HOST'];
$mail->SMTPAuth = true; $mail->SMTPAuth = true;
@@ -132,29 +132,59 @@ try {
$mail->Password = $_ENV['MAIL_PASSWORD']; $mail->Password = $_ENV['MAIL_PASSWORD'];
$mail->SMTPSecure = $_ENV['MAIL_ENCRYPTION']; $mail->SMTPSecure = $_ENV['MAIL_ENCRYPTION'];
$mail->Port = (int) $_ENV['MAIL_PORT']; $mail->Port = (int) $_ENV['MAIL_PORT'];
$mail->Timeout = 5; // Timeout di 5 secondi $mail->Timeout = 5;
$mail->SMTPKeepAlive = false; // Disabilita la connessione persistente $mail->SMTPKeepAlive = true; // una sola connessione per tutti gli invii
$mail->CharSet = 'UTF-8'; // accenti ed emoji corretti
// Mittente
$mail->setFrom($_ENV['MAIL_FROM_ADDRESS'], $_ENV['MAIL_FROM_NAME']); $mail->setFrom($_ENV['MAIL_FROM_ADDRESS'], $_ENV['MAIL_FROM_NAME']);
// Destinatari principali
foreach ($to as $recipient) {
$mail->addAddress($recipient);
}
// Contenuto dell'email
$mail->isHTML(true); $mail->isHTML(true);
$mail->Subject = $subject; $mail->Subject = $subject;
$mail->Body = $emailContent;
$mail->AltBody = strip_tags($emailContent); // Versione testuale dell'email
// Invia l'email $sent = 0;
$mail->send(); $failed = [];
echo json_encode(['success' => true, 'message' => 'Email inviata con successo.']); // Un'email per ogni destinatario: nessuno vede gli indirizzi degli altri
} catch (Exception $e) { foreach ($recipients as $r) {
// Log dell'errore completo $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]);
} catch (\Throwable $e) {
error_log('Errore in send_email.php: ' . $e->getMessage() . ' in ' . $e->getFile() . ' at line ' . $e->getLine()); 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()]); echo json_encode(['success' => false, 'message' => "Errore nell'invio dell'email: " . $e->getMessage()]);
} }
+167 -820
View File
File diff suppressed because it is too large Load Diff