import { NextResponse } from 'next/server'; import { createTransport } from 'nodemailer'; import { cookies } from 'next/headers'; interface StoredCredentials { email: string; password: string; host: string; port: number; } // Maximum attachment size in bytes (10MB) const MAX_ATTACHMENT_SIZE = 10 * 1024 * 1024; function getStoredCredentials(): StoredCredentials | null { const cookieStore = cookies(); const credentialsCookie = cookieStore.get('imap_credentials'); if (!credentialsCookie?.value) { return null; } try { const credentials = JSON.parse(credentialsCookie.value); if (!credentials.email || !credentials.password || !credentials.host || !credentials.port) { return null; } return credentials; } catch (error) { return null; } } export async function POST(request: Request) { try { const credentials = getStoredCredentials(); if (!credentials) { return NextResponse.json( { error: 'No stored credentials found' }, { status: 401 } ); } const { to, cc, bcc, subject, body, attachments } = await request.json(); // Check attachment sizes if (attachments?.length) { const oversizedAttachments = attachments.filter((attachment: any) => { // Calculate size from base64 content const size = Math.ceil((attachment.content.length * 3) / 4); return size > MAX_ATTACHMENT_SIZE; }); if (oversizedAttachments.length > 0) { return NextResponse.json( { error: 'Attachment size limit exceeded', details: { maxSize: MAX_ATTACHMENT_SIZE, oversizedFiles: oversizedAttachments.map((a: any) => a.name) } }, { status: 400 } ); } } // Create a transporter using SMTP with the same credentials // Use port 465 for SMTP (Infomaniak's SMTP port) const transporter = createTransport({ host: credentials.host, port: 465, // SMTP port for Infomaniak secure: true, // Use TLS auth: { user: credentials.email, pass: credentials.password, }, }); // Prepare email options const mailOptions = { from: credentials.email, to, cc, bcc, subject, text: body, attachments: attachments?.map((attachment: any) => ({ filename: attachment.name, content: attachment.content, encoding: attachment.encoding, })), }; // Send the email await transporter.sendMail(mailOptions); return NextResponse.json({ success: true }); } catch (error) { console.error('Error sending email:', error); return NextResponse.json( { error: 'Failed to send email' }, { status: 500 } ); } }