55 lines
1.9 KiB
JavaScript
55 lines
1.9 KiB
JavaScript
#!/usr/bin/env node
|
|
|
|
const { simpleParser } = require('mailparser');
|
|
const db = require('./db');
|
|
|
|
// Using require for get-stream v5 as it's CommonJS
|
|
const getStream = require('get-stream');
|
|
|
|
async function saveEmail(rawEmail) {
|
|
try {
|
|
const parsed = await simpleParser(rawEmail);
|
|
|
|
// Ensure 'to' and 'from' objects exist before accessing 'text'
|
|
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 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);
|
|
// Exit with an error code to signal failure to the calling process (e.g., Mailu)
|
|
process.exit(1);
|
|
}
|
|
}
|
|
|
|
(async () => {
|
|
try {
|
|
const rawEmail = await getStream(process.stdin);
|
|
if (rawEmail && rawEmail.length > 0) {
|
|
await saveEmail(rawEmail);
|
|
} else {
|
|
console.log('Received empty input, no email to save.');
|
|
}
|
|
} catch (error) {
|
|
console.error('Error reading from stdin:', error);
|
|
process.exit(1);
|
|
}
|
|
})();
|