panel 2 courier api

This commit is contained in:
alma 2025-04-25 16:33:03 +02:00
parent b24e266187
commit c9895c1a04

View File

@ -17,8 +17,8 @@ export async function GET(
{ params }: { params: { id: string } } { params }: { params: { id: string } }
) { ) {
try { try {
// 1. Get email ID from params // 1. Get email ID from params (properly awaited)
const { id } = params; const { id } = await Promise.resolve(params);
// 2. Authentication check // 2. Authentication check
const session = await getServerSession(authOptions); const session = await getServerSession(authOptions);
@ -75,53 +75,97 @@ export async function GET(
await client.connect(); await client.connect();
// 7. Open the folder // 7. Open the folder
await client.mailboxOpen(folder); const mailbox = await client.mailboxOpen(folder);
console.log(`Mailbox opened: ${folder}, total messages: ${mailbox.exists}`);
// 8. Fetch the email with UID // 8. Download the raw message data using a dynamic fetch approach
const options = { console.log(`Attempting to fetch message with UID: ${id}`);
uid: true, // This is crucial - we must specify uid:true to fetch by UID
source: true, // Create a loop to process all messages until we find the right one
let foundMessage = null;
const chunkSize = 10;
for (let i = 1; i <= mailbox.exists; i += chunkSize) {
const endIdx = Math.min(i + chunkSize - 1, mailbox.exists);
const range = `${i}:${endIdx}`;
console.log(`Scanning messages ${range}`);
// Fetch messages in chunks with UID
const messages = client.fetch(range, {
uid: true,
envelope: true, envelope: true,
flags: true,
bodyStructure: true, bodyStructure: true,
flags: true source: true
}; });
// Fetch by UID for await (const message of messages) {
const message = await client.fetchOne(id, options); if (message.uid.toString() === id) {
console.log(`Found matching message with UID ${id}`);
foundMessage = message;
break;
}
}
if (!message) { if (foundMessage) {
break;
}
}
if (!foundMessage) {
console.log(`No message found with UID ${id}`);
return NextResponse.json( return NextResponse.json(
{ error: 'Email not found' }, { error: `Email not found with UID ${id}` },
{ status: 404 } { status: 404 }
); );
} }
console.log(`Successfully fetched message, parsing content...`);
// 9. Parse the email content // 9. Parse the email content
const parsedEmail = await parseEmail(message.source.toString()); const parsedEmail = await parseEmail(foundMessage.source.toString());
// 10. Prepare the full email object with all needed data // 10. Prepare the full email object with all needed data
const fullEmail = { const fullEmail = {
id: message.uid.toString(), id,
from: message.envelope.from?.[0]?.address || '', from: foundMessage.envelope.from?.[0]?.address || '',
fromName: message.envelope.from?.[0]?.name || fromName: foundMessage.envelope.from?.[0]?.name ||
message.envelope.from?.[0]?.address?.split('@')[0] || '', foundMessage.envelope.from?.[0]?.address?.split('@')[0] || '',
to: message.envelope.to?.map((addr: any) => addr.address).join(', ') || '', to: foundMessage.envelope.to?.map((addr: any) => addr.address).join(', ') || '',
subject: message.envelope.subject || '(No subject)', subject: foundMessage.envelope.subject || '(No subject)',
date: message.envelope.date?.toISOString() || new Date().toISOString(), date: foundMessage.envelope.date?.toISOString() || new Date().toISOString(),
content: parsedEmail.html || parsedEmail.text || '', content: parsedEmail.html || parsedEmail.text || '',
textContent: parsedEmail.text || '', textContent: parsedEmail.text || '',
read: message.flags.has('\\Seen'), read: foundMessage.flags.has('\\Seen'),
starred: message.flags.has('\\Flagged'), starred: foundMessage.flags.has('\\Flagged'),
folder: folder, folder: folder,
hasAttachments: message.bodyStructure?.type === 'multipart', hasAttachments: foundMessage.bodyStructure?.type === 'multipart',
attachments: parsedEmail.attachments || [], attachments: parsedEmail.attachments || [],
flags: Array.from(message.flags), flags: Array.from(foundMessage.flags),
headers: parsedEmail.headers || {} headers: parsedEmail.headers || {}
}; };
// 11. Mark as read if not already // 11. Mark as read if not already
if (!message.flags.has('\\Seen')) { if (!foundMessage.flags.has('\\Seen')) {
await client.messageFlagsAdd(id, ['\\Seen'], { uid: true }); try {
// Use the same sequence range to mark message as read
for (let i = 1; i <= mailbox.exists; i += chunkSize) {
const endIdx = Math.min(i + chunkSize - 1, mailbox.exists);
const range = `${i}:${endIdx}`;
// Find message and mark as read
const messages = client.fetch(range, { uid: true });
for await (const message of messages) {
if (message.uid.toString() === id) {
await client.messageFlagsAdd(i.toString(), ['\\Seen']);
break;
}
}
}
} catch (error) {
console.error('Error marking message as read:', error);
}
} }
// 12. Cache the email content // 12. Cache the email content