Neah/app/api/mail/mark-read/route.ts
2025-04-21 14:10:00 +02:00

73 lines
1.9 KiB
TypeScript

import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { getImapClient } from '@/lib/imap';
import { ImapFlow } from 'imapflow';
export async function POST(request: Request) {
let client: ImapFlow | null = null;
try {
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
);
}
const { emailId, isRead } = await request.json();
if (!emailId || typeof isRead !== 'boolean') {
return NextResponse.json(
{ error: 'Invalid request parameters' },
{ status: 400 }
);
}
// Get the current folder from the request URL
const url = new URL(request.url);
const folder = url.searchParams.get('folder') || 'INBOX';
try {
client = await getImapClient();
await client.connect();
await client.mailboxOpen(folder);
// Fetch the email to get its UID
const message = await client.fetchOne(emailId.toString(), {
uid: true,
flags: true
});
if (!message) {
return NextResponse.json(
{ error: 'Email not found' },
{ status: 404 }
);
}
// Update the flags
if (isRead) {
await client.messageFlagsAdd(message.uid.toString(), ['\\Seen'], { uid: true });
} else {
await client.messageFlagsRemove(message.uid.toString(), ['\\Seen'], { uid: true });
}
return NextResponse.json({ success: true });
} finally {
if (client) {
try {
await client.logout();
} catch (e) {
console.error('Error during logout:', e);
}
}
}
} catch (error) {
console.error('Error marking email as read:', error);
return NextResponse.json(
{ error: 'Failed to mark email as read' },
{ status: 500 }
);
}
}