diff --git a/lib/services/email-service.ts b/lib/services/email-service.ts index 97a27aa8..264fb0ae 100644 --- a/lib/services/email-service.ts +++ b/lib/services/email-service.ts @@ -271,77 +271,74 @@ export async function getEmails( perPage: number = 20, accountId?: string ): Promise { + const client = await getImapConnection(userId, accountId); + if (!client) { + throw new Error('IMAP client not found'); + } + try { - // Extract the base folder name by removing the accountId suffix if present - const baseFolder = accountId && folder.includes(`-${accountId}`) - ? folder.split(`-${accountId}`)[0] - : folder; - - console.log(`Fetching emails for folder: ${baseFolder} (original: ${folder})`); - - // Get IMAP connection for the account - const imap = await getImapConnection(userId, accountId); - if (!imap) { - throw new Error('Failed to establish IMAP connection'); + // Open the mailbox with the folder name directly + await client.mailboxOpen(folder); + + // Get total message count + const mailbox = client.mailbox; + if (!mailbox || typeof mailbox === 'boolean') { + throw new Error('Failed to open mailbox'); } - - // Open the mailbox - await imap.mailboxOpen(baseFolder); + const total = mailbox.exists || 0; // Calculate message range for pagination - const totalMessages = await imap.status(baseFolder, { messages: true }); - const total = totalMessages.messages || 0; const start = Math.max(1, total - (page * perPage) + 1); const end = Math.max(1, total - ((page - 1) * perPage)); // Fetch messages - const messages = await imap.fetch(`${start}:${end}`, { + const messages = await client.fetch(`${start}:${end}`, { envelope: true, flags: true, - bodyStructure: true, - uid: true + bodyStructure: true }); - + const emails: EmailMessage[] = []; for await (const message of messages) { const email: EmailMessage = { id: message.uid.toString(), - from: (message.envelope?.from || []).map(addr => ({ + from: message.envelope.from?.map(addr => ({ name: addr.name || '', address: addr.address || '' - })), - to: (message.envelope?.to || []).map(addr => ({ + })) || [], + to: message.envelope.to?.map(addr => ({ name: addr.name || '', address: addr.address || '' - })), - subject: message.envelope?.subject || '', - date: message.envelope?.date || new Date(), + })) || [], + subject: message.envelope.subject || '', + date: message.envelope.date || new Date(), flags: { seen: message.flags.has('\\Seen'), - answered: message.flags.has('\\Answered'), flagged: message.flags.has('\\Flagged'), + answered: message.flags.has('\\Answered'), draft: message.flags.has('\\Draft'), deleted: message.flags.has('\\Deleted') }, size: message.size || 0, hasAttachments: message.bodyStructure?.childNodes?.some(node => node.disposition === 'attachment') || false, - folder: folder, + folder, contentFetched: false, accountId: accountId || '', content: '', - messageId: message.envelope?.messageId || undefined + messageId: message.envelope.messageId || undefined }; + emails.push(email); } - - // Cache the result + + // Cache the result if accountId is provided if (accountId) { await cacheEmailList(userId, accountId, folder, page, perPage, emails); } - + // Get mailboxes for this account - const mailboxes = await getMailboxes(imap, accountId); + const mailboxes = await getMailboxes(client, accountId); return { emails, @@ -353,8 +350,14 @@ export async function getEmails( mailboxes }; } catch (error) { - console.error(`Error fetching emails for folder ${folder}:`, error); + console.error('Error fetching emails:', error); throw error; + } finally { + try { + await client.mailboxClose(); + } catch (error) { + console.error('Error closing mailbox:', error); + } } } @@ -603,17 +606,12 @@ export async function getMailboxes(client: ImapFlow, accountId?: string): Promis // Combine standard folders with custom folders const uniqueFolders = new Set([...standardFolders, ...processedMailboxes]); - // If accountId is provided, append it to each folder name - return accountId - ? Array.from(uniqueFolders).map(f => `${f}-${accountId}`) - : Array.from(uniqueFolders); + // Return unique folders without appending accountId + return Array.from(uniqueFolders); } catch (error) { console.error('Error fetching mailboxes:', error); // Return default folders on error - const defaultFolders = ['INBOX', 'Sent', 'Drafts', 'Trash', 'Junk']; - return accountId - ? defaultFolders.map(f => `${f}-${accountId}`) - : defaultFolders; + return ['INBOX', 'Sent', 'Drafts', 'Trash', 'Junk']; } }