NeahNew/app/api/debug-email/route.ts
2025-05-05 13:04:01 +02:00

89 lines
3.2 KiB
TypeScript

import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from "@/app/api/auth/options";
import { getImapConnection } from '@/lib/services/email-service';
import { simpleParser } from 'mailparser';
export async function GET(request: Request) {
// Verify authentication
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
try {
const { searchParams } = new URL(request.url);
const emailId = searchParams.get('id');
const folder = searchParams.get('folder') || 'INBOX';
if (!emailId) {
return NextResponse.json({ error: 'Email ID is required' }, { status: 400 });
}
// Connect to IMAP
const client = await getImapConnection(session.user.id);
try {
await client.mailboxOpen(folder);
// Fetch raw email
const message = await client.fetchOne(emailId, {
source: true,
envelope: true,
flags: true
});
if (!message) {
return NextResponse.json({ error: 'Email not found' }, { status: 404 });
}
// Get raw source content
const { source, envelope } = message;
const rawSource = source.toString();
// Parse the email with multiple options to debug
const parsedEmail = await simpleParser(rawSource, {
skipHtmlToText: true,
keepCidLinks: true
});
// Extract all available data
return NextResponse.json({
id: emailId,
folder,
date: envelope.date,
subject: envelope.subject,
from: envelope.from,
to: envelope.to,
// Raw content (truncated to prevent massive responses)
sourcePreview: rawSource.substring(0, 1000) + (rawSource.length > 1000 ? '...' : ''),
sourceLength: rawSource.length,
// Parsed content
htmlPreview: parsedEmail.html ? parsedEmail.html.substring(0, 1000) + (parsedEmail.html.length > 1000 ? '...' : '') : null,
htmlLength: parsedEmail.html ? parsedEmail.html.length : 0,
textPreview: parsedEmail.text ? parsedEmail.text.substring(0, 1000) + (parsedEmail.text.length > 1000 ? '...' : '') : null,
textLength: parsedEmail.text ? parsedEmail.text.length : 0,
// Detect if there's HTML and what type of content it contains
hasHtml: !!parsedEmail.html,
hasStyleTags: typeof parsedEmail.html === 'string' && parsedEmail.html.includes('<style'),
hasCss: typeof parsedEmail.html === 'string' && parsedEmail.html.includes('style='),
// Headers that might be relevant
contentType: parsedEmail.headers.get('content-type'),
// Attachment count
attachmentCount: parsedEmail.attachments.length
});
} finally {
try {
await client.logout();
} catch (error) {
console.error('Error logging out:', error);
}
}
} catch (error) {
console.error('Error in debug-email route:', error);
return NextResponse.json(
{ error: 'Server error', message: error instanceof Error ? error.message : String(error) },
{ status: 500 }
);
}
}