Files
yogibook_aury_new/public/send_email.php
T
2026-10-05 15:13:05 +02:00

191 lines
5.9 KiB
PHP

<?php
// Includi il file mailer.php per caricare le dipendenze e le variabili .env
require_once 'class/mailer.php';
// Importa le classi necessarie
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
// Imposta l'header per 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
function generateEmailTemplate($message)
{
return <<<HTML
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Email da YogiBook</title>
<style>
body {
font-family: 'Arial', sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
}
.container {
max-width: 600px;
margin: 20px auto;
background-color: #ffffff;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
overflow: hidden;
}
.header {
background-color: #e6f0fa;
padding: 20px;
text-align: center;
}
.header img {
max-width: 100px; /* Ridotto da 150px a 100px per rimpicciolire il logo */
}
.content {
padding: 30px;
color: #333333;
line-height: 1.6;
}
.content p {
margin-bottom: 15px;
}
.footer {
background-color: #e6f0fa;
padding: 15px;
text-align: center;
font-size: 14px;
color: #666666;
}
.footer a {
color: #4a90e2;
text-decoration: none;
}
.footer a:hover {
text-decoration: underline;
}
.yoga-decoration {
width: 100%;
height: 10px;
background: linear-gradient(to right, #4a90e2, #87ceeb);
}
</style>
</head>
<body>
<div class="container">
<div class="yoga-decoration"></div>
<div class="header">
<img src="https://yogasoul.it/wp-content/uploads/2021/03/logotransizione_final2.png"
alt="YogaSoul - My WordPress Blog"
width="120"
style="display: block; width: 120px; max-width: 120px; height: auto; margin: 0 auto;">
</div>
<div class="content">
<p>$message</p>
</div>
<div class="footer">
<p>Ti aspettiamo alla tua prossima lezione di yoga!</p>
<p><a href="https://yogasoul.it">YogaSoul</a> | <a href="mailto:info@yogasoul.it">Contattaci</a></p>
</div>
<div class="yoga-decoration"></div>
</div>
</body>
</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
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]);
} 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()]);
}