Neah/app/api/courrier/[id]/mark-read/route.ts
2025-04-25 17:36:12 +02:00

77 lines
1.9 KiB
TypeScript

import { NextResponse } from 'next/server';
import { ImapFlow } from 'imapflow';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
import { prisma } from '@/lib/prisma';
export async function POST(
request: Request,
{ params }: { params: { id: string } }
) {
try {
const { id } = await Promise.resolve(params);
// Authentication check
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
);
}
// Get credentials from database
const credentials = await prisma.mailCredentials.findUnique({
where: {
userId: session.user.id
}
});
if (!credentials) {
return NextResponse.json(
{ error: 'No mail credentials found. Please configure your email account.' },
{ status: 401 }
);
}
// Create IMAP client
const client = new ImapFlow({
host: credentials.host,
port: credentials.port,
secure: true,
auth: {
user: credentials.email,
pass: credentials.password,
},
logger: false,
emitLogs: false,
tls: {
rejectUnauthorized: false
}
});
try {
await client.connect();
// Open INBOX
await client.mailboxOpen('INBOX');
// Mark the email as read
await client.messageFlagsAdd(id, ['\\Seen'], { uid: true });
return NextResponse.json({ success: true });
} finally {
try {
await client.logout();
} catch (e) {
console.error('Error during IMAP logout:', e);
}
}
} catch (error) {
console.error('Error marking email as read:', error);
return NextResponse.json(
{ error: 'Failed to mark email as read' },
{ status: 500 }
);
}
}