import { config } from "./src/config.ts"; import {ImapFlow, type MailboxLockObject} from "imapflow"; import { extract } from 'letterparser' import {ReplyParser} from "./src/mail/replies.ts"; import type {Message} from "./src/types.ts"; import type {Awaitable} from "./src/bones"; import {AsyncCollection} from "./src/bones/collection/AsyncCollection.ts"; import {AsyncGeneratorIterable} from "./src/bones/collection/AsyncGeneratorIterable.ts"; export async function withMessageClient(cb: (c: ImapFlow) => Awaitable): Promise { const client = new ImapFlow(config.mail.imap) await client.connect() try { return cb(client) } finally { await client.logout() } } export async function getFolders(): Promise { return withMessageClient(async client => { const list = await client.list() return list.map(l => l.name) }) } export const getMessagesForMailbox = (box: string): AsyncCollection => { return new AsyncCollection( new AsyncGeneratorIterable( () => getMessagesForMailboxOld(box))) } export async function* getMessagesForMailboxOld(box: string): AsyncGenerator { const client = new ImapFlow(config.mail.imap) await client.connect() try { let lock: MailboxLockObject try { lock = await client.getMailboxLock(box) } catch (e: unknown) { // This is usually because the mailbox does not exist, so yield nothing console.warn(`Error when opening mailbox lock for mailbox "${box}":\n`, e) return } try { await client.mailboxOpen(box) const messages = client.fetch('1:*', { envelope: true, source: true, uid: true, bodyParts: ['text'], }) for await ( const message of messages ) { const source = message.source.toString('utf-8') const content = ReplyParser.parseReply(extract(source).text || '') const msg: Message = { id: message.envelope.messageId, date: message.envelope.date, recipients: message.envelope.to.map(x => x.address || '').filter(Boolean), from: message.envelope.from[0], subject: message.envelope.subject, content, } yield msg } } finally { lock.release() } } finally { await client.logout() } } const c = getMessagesForMailbox('e12a') console.log(await c.all())