67 lines
1.5 KiB
TypeScript
67 lines
1.5 KiB
TypeScript
import { ImapFlow } from 'imapflow';
|
|
import { simpleParser } from 'mailparser';
|
|
|
|
export interface EmailData {
|
|
from: string;
|
|
subject: string;
|
|
text: string;
|
|
html?: string;
|
|
date: Date;
|
|
}
|
|
|
|
export async function getLatestEmail(email: string, password: string): Promise<EmailData | null> {
|
|
const host = process.env.MAILCOW_HOSTNAME || email.split('@')[1];
|
|
|
|
const client = new ImapFlow({
|
|
host: host,
|
|
port: 993,
|
|
secure: true,
|
|
auth: {
|
|
user: email,
|
|
pass: password
|
|
},
|
|
logger: false
|
|
});
|
|
|
|
try {
|
|
await client.connect();
|
|
|
|
// Select INBOX
|
|
let lock = await client.getMailboxLock('INBOX');
|
|
try {
|
|
// Find the last message
|
|
const messages = await client.fetch('1:*', {
|
|
envelope: true,
|
|
source: true,
|
|
});
|
|
|
|
// imapflow fetch returns an async generator or array?
|
|
// Actually fetch() returns an async iterator.
|
|
let lastMsg = null;
|
|
for await (const msg of messages) {
|
|
lastMsg = msg;
|
|
}
|
|
|
|
if (lastMsg && lastMsg.source) {
|
|
const parsed = await simpleParser(lastMsg.source);
|
|
return {
|
|
from: parsed.from?.text || '',
|
|
subject: parsed.subject || '',
|
|
text: parsed.text || '',
|
|
html: parsed.html || undefined,
|
|
date: parsed.date || new Date()
|
|
};
|
|
}
|
|
} finally {
|
|
lock.release();
|
|
}
|
|
|
|
await client.logout();
|
|
} catch (err) {
|
|
console.error(`[IMAP] Error fetching mail for ${email}:`, err);
|
|
return null;
|
|
}
|
|
|
|
return null;
|
|
}
|