diff --git a/lib/services/email-service.ts b/lib/services/email-service.ts index 760c5434..a6ecb9b5 100644 --- a/lib/services/email-service.ts +++ b/lib/services/email-service.ts @@ -272,13 +272,15 @@ export async function getEmails( perPage: number = 20, accountId?: string ): Promise { + 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})`); // Get IMAP connection - const client = await getImapConnection(userId, accountId); + client = await getImapConnection(userId, accountId); if (!client) { throw new Error('Failed to establish IMAP connection'); } @@ -379,10 +381,12 @@ export async function getEmails( console.error('Error fetching emails:', error); throw error; } finally { - try { - await client?.mailboxClose(); - } catch (error) { - console.error('Error closing mailbox:', error); + if (client) { + try { + await client.mailboxClose(); + } catch (error) { + console.error('Error closing mailbox:', error); + } } } }