Implement mail signal webhook and IMAP mail fetching logic
This commit is contained in:
66
lib/mail.ts
Normal file
66
lib/mail.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
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;
|
||||
}
|
||||
Reference in New Issue
Block a user