Neah/app/api/mail/route.ts
2025-04-21 12:40:12 +02:00

108 lines
3.1 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() {
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 }
);
}
// 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();
const mailbox = await client.mailboxOpen('INBOX');
// Fetch messages with body content
const messages = await client.fetch('1:20', {
envelope: true,
flags: true,
bodyStructure: true,
bodyParts: ['TEXT']
});
const result = [];
for await (const message of messages) {
// Get the body content
let body = '';
if (message.bodyParts && Array.isArray(message.bodyParts)) {
for (const [partType, content] of message.bodyParts) {
if (partType === 'text') {
body = content.toString('utf-8');
break;
}
}
}
result.push({
id: message.uid.toString(),
accountId: 1, // Default account ID
from: message.envelope.from?.[0]?.address || '',
fromName: message.envelope.from?.[0]?.name || message.envelope.from?.[0]?.address?.split('@')[0] || '',
to: message.envelope.to?.[0]?.address || '',
subject: message.envelope.subject || '(No subject)',
body: body,
date: message.envelope.date.toISOString(),
read: message.flags.has('\\Seen'),
starred: message.flags.has('\\Flagged'),
folder: mailbox.path,
cc: message.envelope.cc?.map(addr => addr.address).join(', '),
bcc: message.envelope.bcc?.map(addr => addr.address).join(', '),
flags: Array.from(message.flags)
});
}
return NextResponse.json({
emails: result,
folders: ['INBOX', 'Sent', 'Drafts', 'Trash', 'Spam']
});
} finally {
try {
await client.logout();
} catch (e) {
console.error('Error during logout:', e);
}
}
} catch (error) {
console.error('Error in mail route:', error);
return NextResponse.json(
{ error: 'An unexpected error occurred' },
{ status: 500 }
);
}
}