-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsend_mail_handler.php
More file actions
351 lines (318 loc) · 13.5 KB
/
Copy pathsend_mail_handler.php
File metadata and controls
351 lines (318 loc) · 13.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
<?php
header('Content-Type: application/json; charset=utf-8');
require 'includes/db.php';
// Only allow AJAX POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['success' => false, 'message' => 'Invalid request method']);
exit();
}
// Check admin
if (!isset($_SESSION['user_id']) || ($_SESSION['role'] ?? '') !== 'admin') {
http_response_code(403);
echo json_encode(['success' => false, 'message' => 'Access denied']);
exit();
}
// CSRF token
$csrf = $_POST['csrf_token'] ?? '';
if (empty($csrf) || !hash_equals($_SESSION['csrf_mail_token'] ?? '', $csrf)) {
echo json_encode(['success' => false, 'message' => 'Invalid CSRF token']);
exit();
}
// Basic input validation and sanitization
$title = trim($_POST['mail_title'] ?? '');
$subject = trim($_POST['mail_subject'] ?? '');
$body = trim($_POST['mail_body'] ?? '');
$overall = isset($_POST['overall_students']) && ($_POST['overall_students'] == '1' || $_POST['overall_students'] === 'on');
$recipient_mode = in_array($_POST['recipient_mode'] ?? '', ['overall','particular','manual'], true) ? $_POST['recipient_mode'] : 'overall';
// handle multiple selection: student_ids[] expected for particular
$student_ids_raw = $_POST['student_ids'] ?? [];
if (!is_array($student_ids_raw) && $student_ids_raw !== '') {
// single value
$student_ids_raw = [$student_ids_raw];
}
$student_ids = array_values(array_filter(array_map('intval', (array)$student_ids_raw)));
if ($title === '' || $subject === '' || $body === '') {
echo json_encode(['success' => false, 'message' => 'Title, subject and body are required']);
exit();
}
// Determine recipients
$recipients = [];
try {
if ($recipient_mode === 'particular') {
if (empty($student_ids)) {
echo json_encode(['success' => false, 'message' => 'Please select at least one student']);
exit();
}
// Build placeholders for IN clause
$placeholders = implode(',', array_fill(0, count($student_ids), '?'));
$stmt = $pdo->prepare("SELECT user_id, full_name, email FROM students WHERE user_id IN ($placeholders) AND email IS NOT NULL AND email != ''");
$stmt->execute($student_ids);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($rows) {
// use the fetched rows as recipients
$recipients = $rows;
} else {
echo json_encode(['success' => false, 'message' => 'Selected student(s) not found or have no email']);
exit();
}
} elseif ($recipient_mode === 'manual') {
$manual_raw = $_POST['manual_emails'] ?? '';
$parts = preg_split('/[,\r\n;]+/', $manual_raw);
$parts = array_map('trim', $parts);
$parts = array_values(array_filter($parts));
$valid = [];
foreach ($parts as $p) {
if (filter_var($p, FILTER_VALIDATE_EMAIL)) {
// attempt to make a readable name from local-part
$local = explode('@', $p, 2)[0];
$name = preg_replace('/[._0-9-]+/', ' ', $local);
$name = trim(ucwords($name)) ?: 'Student';
$valid[] = ['full_name' => $name, 'email' => $p];
}
}
if (empty($valid)) {
echo json_encode(['success' => false, 'message' => 'No valid manual email addresses provided']);
exit();
}
$recipients = $valid;
} else {
// overall students checkbox must be checked to send to all
if (!$overall) {
echo json_encode(['success' => false, 'message' => 'No recipient selection made']);
exit();
}
$stmt = $pdo->query("SELECT full_name, email FROM students WHERE email IS NOT NULL AND email != ''");
$recipients = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (empty($recipients)) {
echo json_encode(['success' => false, 'message' => 'No recipients found']);
exit();
}
}
} catch (PDOException $e) {
error_log("Recipients error: " . $e->getMessage());
echo json_encode(['success' => false, 'message' => 'Database error']);
exit();
}
// Attachment handling (multiple files support)
$attachment_paths = []; // full paths on disk
$attachment_basenames = []; // original/safe basenames
if (isset($_FILES['attachments'])) {
$files = $_FILES['attachments'];
// normalize array structure
$count = is_array($files['name']) ? count($files['name']) : 0;
$upload_dir = __DIR__ . DIRECTORY_SEPARATOR . 'assets' . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'mail_attachments' . DIRECTORY_SEPARATOR;
if (!is_dir($upload_dir) && !mkdir($upload_dir, 0755, true)) {
echo json_encode(['success' => false, 'message' => 'Failed to create upload directory']);
exit();
}
$finfo = new finfo(FILEINFO_MIME_TYPE);
$allowed_mimes = [
'image/jpeg',
'image/png',
'application/pdf',
'application/msword',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/zip',
'application/x-rar-compressed',
'application/vnd.ms-powerpoint',
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'text/plain',
'text/csv'
];
for ($i = 0; $i < $count; $i++) {
$error = $files['error'][$i] ?? UPLOAD_ERR_NO_FILE;
if ($error !== UPLOAD_ERR_OK) {
// skip files with no upload or error; optionally collect errors
continue;
}
$size = $files['size'][$i] ?? 0;
if ($size > 10 * 1024 * 1024) {
// skip oversized file
continue;
}
$tmp = $files['tmp_name'][$i];
$mime = $finfo->file($tmp);
if (!in_array($mime, $allowed_mimes, true)) {
// skip disallowed mime
continue;
}
$original_name = basename($files['name'][$i]);
$safe_name = preg_replace('/[^A-Za-z0-9._-]/', '_', $original_name);
$target = $upload_dir . $safe_name;
if (file_exists($target)) {
$ext = pathinfo($safe_name, PATHINFO_EXTENSION);
$name_no_ext = pathinfo($safe_name, PATHINFO_FILENAME);
$safe_name = $name_no_ext . '-' . time() . '-' . $i . ($ext ? '.' . $ext : '');
$target = $upload_dir . $safe_name;
}
if (move_uploaded_file($tmp, $target)) {
$attachment_paths[] = $target;
$attachment_basenames[] = $safe_name;
}
}
}
// PHPMailer - include and use
require 'includes/PHPMailer/Exception.php';
require 'includes/PHPMailer/PHPMailer.php';
require 'includes/PHPMailer/SMTP.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
// Load SMTP config from environment variables
$mailHost = env('SMTP_HOST', 'smtp.gmail.com');
$mailUser = env('SMTP_USERNAME', '');
$mailPass = env('SMTP_PASSWORD', '');
$mailPort = (int) env('SMTP_PORT', 587);
$mailFrom = env('SMTP_FROM', env('SMTP_USERNAME', ''));
$mailFromName = env('SMTP_FROM_NAME', 'CAI ADMIN');
// Build absolute URL to logo for inline display (no embedding)
$baseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http')
. '://' . $_SERVER['HTTP_HOST']
. rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\') . '/';
$logo_url = $baseUrl . 'assets/images/logo1.png';
// Initialize PHPMailer once and reuse SMTP connection
$sent = 0;
$failed = 0;
$failed_list = [];
try {
$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->Host = $mailHost;
$mail->SMTPAuth = true;
$mail->Username = $mailUser;
$mail->Password = $mailPass;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = $mailPort;
$mail->CharSet = 'UTF-8';
$mail->setFrom($mailFrom, $mailFromName);
$mail->addReplyTo($mailFrom, $mailFromName);
$mail->isHTML(true);
$mail->Subject = $subject;
// Keep SMTP connection open for multiple sends
$mail->SMTPKeepAlive = true;
// Do not show debug output in production; keep 0
$mail->SMTPDebug = 0;
// Server path to logo (used for embedding)
$logo_path = __DIR__ . DIRECTORY_SEPARATOR . 'assets' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'logo1.png';
$logo_cid = 'logo_cid';
$logo_embedded = false;
if (file_exists($logo_path)) {
try {
// embed once (we may re-add per-loop if we clear attachments)
$mail->addEmbeddedImage($logo_path, $logo_cid, basename($logo_path));
$logo_embedded = true;
} catch (Exception $e) {
error_log("Embed logo failed: " . $e->getMessage());
$logo_embedded = false;
}
}
foreach ($recipients as $r) {
try {
// clear only recipients/attachments/custom headers so we add fresh per-recipient attachments
$mail->clearAddresses();
$mail->clearAttachments();
$mail->clearCustomHeaders();
// re-add embedded logo if cleared above
if ($logo_embedded && file_exists($logo_path)) {
try {
$mail->addEmbeddedImage($logo_path, $logo_cid, basename($logo_path));
} catch (Exception $e) {
error_log("Re-embed logo failed: " . $e->getMessage());
$logo_embedded = false;
}
}
// add recipient
$mail->addAddress($r['email'], $r['full_name']);
// Personalize body:
// If user used {student_name} placeholder in the body, replace it.
// Otherwise, prepend "Dear <name>,"
$personalized_plain = $body;
if (strpos($body, '{student_name}') !== false) {
$personalized_plain = str_replace('{student_name}', $r['full_name'], $body);
} else {
$personalized_plain = "Dear " . $r['full_name'] . ",\n\n" . $body;
}
// Escape and generate HTML
$personal_html_body = nl2br(htmlspecialchars($personalized_plain, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'));
// Compose full HTML email (embed logo via CID if available, otherwise fallback to URL)
if ($logo_embedded) {
$header_logo_html = '<img src="cid:' . $logo_cid . '" class="email-logo" alt="Logo" style="width:72px;height:72px;display:block;margin:0 auto 0.5rem;">';
} else {
$header_logo_html = '<img src="' . htmlspecialchars($logo_url, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '" class="email-logo" alt="Logo" style="width:72px;height:72px;display:block;margin:0 auto 0.5rem;">';
}
$personal_html = <<<HTML
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
body{font-family:Arial,Helvetica,sans-serif;color:#333;line-height:1.6}
.header{background:linear-gradient(135deg,#667eea,#764ba2);color:#fff;padding:24px;text-align:center}
.content{padding:18px;background:#f8f9fa}
.footer{background:#343a40;color:#fff;padding:12px;text-align:center;font-size:0.9rem}
</style>
</head>
<body>
<div class="header">{$header_logo_html}<h2>{$title}</h2></div>
<div class="content">{$personal_html_body}</div>
<div class="footer"><p><strong>SIETK - III CAI Portal</strong><br>Computer Science & Engineering(Artificial Intelligence)<br>Email: {$mailFrom}</p></div>
</body>
</html>
HTML;
$mail->Body = $personal_html;
$mail->AltBody = strip_tags($personalized_plain);
// attachment(s) if present
if (!empty($attachment_paths)) {
foreach ($attachment_paths as $idx => $apath) {
if (file_exists($apath)) {
$aname = $attachment_basenames[$idx] ?? basename($apath);
$mail->addAttachment($apath, $aname);
}
}
}
// send and capture errors
if ($mail->send()) {
$sent++;
} else {
$failed++;
$failed_list[] = ['email' => $r['email'], 'error' => $mail->ErrorInfo ?: 'Unknown error'];
error_log("Mail send failed for {$r['email']}: " . ($mail->ErrorInfo ?? 'No ErrorInfo'));
}
} catch (Exception $e) {
$failed++;
$failed_list[] = ['email' => $r['email'], 'error' => $e->getMessage()];
error_log("Mail error to {$r['email']}: " . $e->getMessage());
}
}
// Close SMTP connection
try { $mail->smtpClose(); } catch (\Exception $e) {}
// Clean up attachment(s) on disk
if (!empty($attachment_paths)) {
foreach ($attachment_paths as $p) {
if (file_exists($p)) @unlink($p);
}
}
$total = count($recipients);
$message = "Emails processed: {$sent}/{$total} sent.";
if ($failed > 0) {
$short = array_map(function($f){ return $f['email'] . ($f['error'] ? " ({$f['error']})" : ''); }, array_slice($failed_list, 0, 5));
$message .= " Failed: " . implode(', ', $short);
if ($failed > 5) $message .= " and " . ($failed - 5) . " more";
}
// Consider the operation successful only when there are no failures
$success = ($failed === 0);
echo json_encode(['success' => $success, 'message' => $message, 'stats' => ['total' => $total, 'sent' => $sent, 'failed' => $failed]]);
exit();
} catch (Exception $e) {
error_log("PHPMailer init error: " . $e->getMessage());
if (!empty($attachment_paths)) {
foreach ($attachment_paths as $p) {
if (file_exists($p)) {
@unlink($p);
}
}
}
echo json_encode(['success' => false, 'message' => 'Mail server error: ' . $e->getMessage()]);
exit();
}
?>