exec(" CREATE TABLE emails ( id INTEGER PRIMARY KEY AUTOINCREMENT, direction TEXT CHECK(direction IN ('incoming', 'outgoing')) NOT NULL, user TEXT, domain TEXT, subject TEXT, date TEXT, attachments_no INTEGER, sizeKb INTEGER ) "); } // Extract local part and domain from the email address $local = preg_replace('/[^a-zA-Z0-9_.+-]/', '_', strstr($email, '@', true)); $domain = preg_replace('/[^a-zA-Z0-9_.+-]/', '_', substr(strstr($email, '@'), 1)); // Attempt to parse the Subject header from the raw message $subject = ''; if (preg_match('/^Subject:\s*(.*)$/mi', $raw_msg, $matches)) { $subject = trim($matches[1]); } // Calculate message size in kilobytes $size_kb = (int)(strlen($raw_msg) / 1024); // Use the current timestamp as the 'date' $timestamp = date('Y-m-d H:i:s'); // Prepare and execute the insert query $stmt = $db->prepare(" INSERT INTO emails (direction, user, domain, subject, date, attachments_no, sizeKb) VALUES (:direction, :user, :domain, :subject, :date, :attachments, :size) "); $stmt->bindValue(':direction', $direction, SQLITE3_TEXT); $stmt->bindValue(':user', $local, SQLITE3_TEXT); $stmt->bindValue(':domain', $domain, SQLITE3_TEXT); $stmt->bindValue(':subject', $subject, SQLITE3_TEXT); $stmt->bindValue(':date', $timestamp, SQLITE3_TEXT); $stmt->bindValue(':attachments', 0, SQLITE3_INTEGER); // Can be extended later to count real attachments $stmt->bindValue(':size', $size_kb, SQLITE3_INTEGER); $stmt->execute(); // Close the database connection $db->close(); } catch (Exception $e) { // Log any unexpected SQLite errors (e.g., permission issues) error_log("SQLite error: " . $e->getMessage()); } }