diff --git a/server/src/nest/mail-ingest/mail-ingest-imap.client.ts b/server/src/nest/mail-ingest/mail-ingest-imap.client.ts index ec503dcc7..f35b556e8 100644 --- a/server/src/nest/mail-ingest/mail-ingest-imap.client.ts +++ b/server/src/nest/mail-ingest/mail-ingest-imap.client.ts @@ -121,6 +121,18 @@ class ImapFlowSession implements ImapSession { const existing = await this.findFolder(parts); if (existing !== null) return existing; + try { + return await this.createFolder(parts); + } catch (err) { + // Some servers require the parent to be created separately. + const parent = parts.slice(0, -1); + if (parent.length === 0 || (await this.findFolder(parent)) !== null) throw err; + await this.createFolder(parent); + return this.createFolder(parts); + } + } + + private async createFolder(parts: readonly string[]): Promise { try { const created = await this.client.mailboxCreate([...parts]); return created.path; diff --git a/server/tests/unit/nest/mail-ingest/mail-ingest-imap.client.test.ts b/server/tests/unit/nest/mail-ingest/mail-ingest-imap.client.test.ts index 1ac623c11..cce9fcb40 100644 --- a/server/tests/unit/nest/mail-ingest/mail-ingest-imap.client.test.ts +++ b/server/tests/unit/nest/mail-ingest/mail-ingest-imap.client.test.ts @@ -139,6 +139,20 @@ describe('MailIngestImapClient', () => { expect(reason).toBe('Could not create IMAP folder TREK/processed. The IMAP server answered: CREATE failed'); }); + it('creates a missing parent when the server refuses to create the child first', async () => { + const session = await new MailIngestImapClient().connect(CONFIG); + flow.status + .mockRejectedValueOnce(missingFolder()) + .mockRejectedValueOnce(missingFolder()) + .mockRejectedValueOnce(missingFolder()); + flow.mailboxCreate + .mockRejectedValueOnce(new Error('CREATE failed')) + .mockResolvedValueOnce({ path: 'TREK', created: true }); + + await expect(session.ensureFolder(['TREK', 'processed'])).resolves.toBe('TREK.processed'); + expect(flow.mailboxCreate.mock.calls).toEqual([[['TREK', 'processed']], [['TREK']], [['TREK', 'processed']]]); + }); + it('does not ask an empty folder for a range', async () => { flow.mailboxOpen.mockResolvedValueOnce({ uidValidity: 5n, exists: 0 }); const session = await new MailIngestImapClient().connect(CONFIG);