const { simpleParser } = require('mailparser'); const db = require('./db'); async function saveEmail(stream) { try { const parsed = await simpleParser(stream); const rawEmail = stream.toString(); // Or handle stream to buffer conversion appropriately const recipient = parsed.to ? parsed.to.text : 'undisclosed-recipients'; const sender = parsed.from ? parsed.from.text : 'unknown-sender'; const subject = parsed.subject; const body = parsed.text || (parsed.html || ''); const [result] = await db.execute( 'INSERT INTO emails (recipient, sender, subject, body, raw) VALUES (?, ?, ?, ?, ?)', [recipient, sender, subject, body, rawEmail] ); console.log(`Email from <${sender}> to <${recipient}> saved with ID: ${result.insertId}`); if (parsed.attachments && parsed.attachments.length > 0) { for (const attachment of parsed.attachments) { await db.execute( 'INSERT INTO email_attachments (email_id, filename, content_type, content) VALUES (?, ?, ?, ?)', [result.insertId, attachment.filename, attachment.contentType, attachment.content] ); console.log(`Attachment ${attachment.filename} saved.`); } } } catch (error) { console.error('Failed to save email:', error); // We should not exit the process here, but maybe throw the error // so the caller (SMTPServer) can handle it. throw error; } } module.exports = { saveEmail };