diff --git a/lib/services/email-service.ts b/lib/services/email-service.ts index c938b169..b1db1172 100644 --- a/lib/services/email-service.ts +++ b/lib/services/email-service.ts @@ -275,9 +275,9 @@ export async function getEmails( let client: ImapFlow | undefined; try { - // Extract base folder name (remove accountId suffix if present) - const baseFolder = folder.split('-')[0]; - console.log(`Fetching emails for folder: ${folder} (base: ${baseFolder})`); + // Extract the actual folder name (remove account prefix if present) + const actualFolder = folder.includes(':') ? folder.split(':')[1] : folder; + console.log(`Fetching emails for folder: ${folder} (actual: ${actualFolder})`); // Get IMAP connection client = await getImapConnection(userId, accountId); @@ -285,16 +285,16 @@ export async function getEmails( throw new Error('Failed to establish IMAP connection'); } - // Open mailbox - await client.mailboxOpen(baseFolder); + // Open mailbox with the actual folder name + await client.mailboxOpen(actualFolder); const mailbox = client.mailbox; if (!mailbox || typeof mailbox === 'boolean') { - throw new Error(`Failed to open mailbox: ${baseFolder}`); + throw new Error(`Failed to open mailbox: ${actualFolder}`); } // Get total messages const total = mailbox.exists || 0; - console.log(`Total messages in ${baseFolder}: ${total}`); + console.log(`Total messages in ${actualFolder}: ${total}`); // If no messages, return empty result if (total === 0) { @@ -304,7 +304,7 @@ export async function getEmails( page, perPage, totalPages: 0, - folder: baseFolder, + folder: actualFolder, mailboxes: [] }; } @@ -312,7 +312,7 @@ export async function getEmails( // Calculate message range for pagination const start = Math.max(1, total - (page * perPage) + 1); const end = Math.max(1, total - ((page - 1) * perPage)); - console.log(`Fetching messages ${start}:${end} from ${baseFolder}`); + console.log(`Fetching messages ${start}:${end} from ${actualFolder}`); // Fetch messages const messages = await client.fetch(`${start}:${end}`, { @@ -344,7 +344,7 @@ export async function getEmails( }, size: message.size || 0, hasAttachments: message.bodyStructure?.childNodes?.some(node => node.disposition === 'attachment') || false, - folder: baseFolder, + folder: actualFolder, contentFetched: false, accountId: accountId || 'default', content: { @@ -357,13 +357,13 @@ export async function getEmails( // Cache the result if we have an accountId if (accountId) { - await cacheEmailList(userId, accountId, baseFolder, page, perPage, { + await cacheEmailList(userId, accountId, actualFolder, page, perPage, { emails, totalEmails: total, page, perPage, totalPages: Math.ceil(total / perPage), - folder: baseFolder, + folder: actualFolder, mailboxes: [] }); } @@ -374,7 +374,7 @@ export async function getEmails( page, perPage, totalPages: Math.ceil(total / perPage), - folder: baseFolder, + folder: actualFolder, mailboxes: [] }; } catch (error) {