99 lines
2.7 KiB
TypeScript
99 lines
2.7 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 GET(request: Request, { params }: { params: { id: string } }) {
|
|
try {
|
|
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 }
|
|
);
|
|
}
|
|
|
|
// Get the current folder from the request URL
|
|
const url = new URL(request.url);
|
|
const folder = url.searchParams.get('folder') || 'INBOX';
|
|
|
|
// Connect to IMAP server
|
|
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();
|
|
await client.mailboxOpen(folder);
|
|
|
|
// Fetch the full email content
|
|
const message = await client.fetchOne(params.id, {
|
|
source: true,
|
|
envelope: true,
|
|
flags: true
|
|
});
|
|
|
|
if (!message) {
|
|
return NextResponse.json(
|
|
{ error: 'Email not found' },
|
|
{ status: 404 }
|
|
);
|
|
}
|
|
|
|
// Extract email content
|
|
const result = {
|
|
id: message.uid.toString(),
|
|
from: message.envelope.from[0].address,
|
|
subject: message.envelope.subject || '(No subject)',
|
|
date: message.envelope.date.toISOString(),
|
|
read: message.flags.has('\\Seen'),
|
|
starred: message.flags.has('\\Flagged'),
|
|
folder: folder,
|
|
body: message.source.toString(),
|
|
to: message.envelope.to?.map(addr => addr.address).join(', ') || '',
|
|
cc: message.envelope.cc?.map(addr => addr.address).join(', ') || '',
|
|
bcc: message.envelope.bcc?.map(addr => addr.address).join(', ') || '',
|
|
};
|
|
|
|
return NextResponse.json(result);
|
|
} finally {
|
|
try {
|
|
await client.logout();
|
|
} catch (e) {
|
|
console.error('Error during logout:', e);
|
|
}
|
|
}
|
|
} catch (error) {
|
|
console.error('Error fetching email:', error);
|
|
return NextResponse.json(
|
|
{ error: 'An unexpected error occurred' },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|