import { NextResponse } from 'next/server'; import { cookies } from 'next/headers'; import { ImapFlow } from 'imapflow'; export async function GET() { try { const cookieStore = cookies(); const credentials = cookieStore.get('imap_credentials'); if (!credentials) { return NextResponse.json( { error: 'No credentials found. Please login to your email account first.' }, { status: 401 } ); } let client; try { const { email, password, host, port } = JSON.parse(credentials.value); client = new ImapFlow({ host, port: parseInt(port), secure: true, auth: { user: email, pass: password, }, logger: false, emitLogs: false }); await client.connect(); const mailbox = await client.mailboxOpen('INBOX'); const messages = await client.fetch('1:10', { envelope: true }); const result = []; for await (const message of messages) { result.push({ id: message.uid, subject: message.envelope.subject, from: message.envelope.from[0].address, date: message.envelope.date, }); } return NextResponse.json(result); } catch (error) { console.error('Mail API error:', error); if (error instanceof Error) { if (error.message.includes('Invalid login')) { return NextResponse.json( { error: 'Invalid email credentials. Please login again.' }, { status: 401 } ); } return NextResponse.json( { error: `Failed to fetch emails: ${error.message}` }, { status: 500 } ); } return NextResponse.json( { error: 'Failed to fetch emails' }, { status: 500 } ); } finally { if (client) { try { await client.logout(); } catch (e) { console.error('Error during logout:', e); } } } } catch (error) { console.error('Unexpected error:', error); return NextResponse.json( { error: 'An unexpected error occurred' }, { status: 500 } ); } }