Neah/app/api/courrier/test-connection/route.ts
2025-04-27 16:12:04 +02:00

137 lines
3.9 KiB
TypeScript

import { NextResponse } from 'next/server';
import { ImapFlow } from 'imapflow';
import nodemailer from 'nodemailer';
export async function POST(request: Request) {
try {
// Parse request body
const body = await request.json().catch(e => {
console.error('Error parsing request body:', e);
return {};
});
// Log request but hide password
console.log('Testing connection with:', {
...body,
password: body.password ? '***' : undefined
});
const { email, password, host, port, secure = true } = body;
// Validate required fields
if (!email || !password || !host || !port) {
const missing = [];
if (!email) missing.push('email');
if (!password) missing.push('password');
if (!host) missing.push('host');
if (!port) missing.push('port');
return NextResponse.json(
{ error: `Missing required fields: ${missing.join(', ')}` },
{ status: 400 }
);
}
// Fix common hostname errors - strip http/https prefixes
let cleanHost = host;
if (cleanHost.startsWith('http://')) {
cleanHost = cleanHost.substring(7);
} else if (cleanHost.startsWith('https://')) {
cleanHost = cleanHost.substring(8);
}
console.log(`Testing IMAP connection to ${cleanHost}:${port} for ${email}`);
// Test IMAP connection
const client = new ImapFlow({
host: cleanHost,
port: typeof port === 'string' ? parseInt(port) : port,
secure: secure === true || secure === 'true',
auth: {
user: email,
pass: password,
},
logger: false,
tls: {
rejectUnauthorized: false
},
// Set timeout to prevent long waits
connectionTimeout: 10000
});
try {
await client.connect();
console.log(`IMAP connection successful for ${email}`);
// Try to list mailboxes
const mailboxes = await client.list();
const folderNames = mailboxes.map(mailbox => mailbox.path);
console.log(`Found ${folderNames.length} folders:`, folderNames.slice(0, 5));
try {
await client.logout();
} catch (e) {
// Ignore logout errors
}
return NextResponse.json({
success: true,
message: 'IMAP connection successful',
details: {
host: cleanHost,
port,
folderCount: folderNames.length,
sampleFolders: folderNames.slice(0, 5)
}
});
} catch (error) {
console.error('IMAP connection test failed:', error);
let friendlyMessage = 'Connection failed';
let errorDetails = '';
if (error instanceof Error) {
errorDetails = error.message;
if (error.message.includes('Invalid login') || error.message.includes('authentication failed')) {
friendlyMessage = 'Invalid username or password';
} else if (error.message.includes('ENOTFOUND') || error.message.includes('ECONNREFUSED')) {
friendlyMessage = 'Cannot connect to server - check host and port';
} else if (error.message.includes('certificate')) {
friendlyMessage = 'SSL/TLS certificate issue';
} else if (error.message.includes('timeout')) {
friendlyMessage = 'Connection timed out';
}
}
try {
await client.logout();
} catch (e) {
// Ignore logout errors
}
return NextResponse.json(
{
error: friendlyMessage,
details: errorDetails,
debug: {
providedHost: host,
cleanHost,
port,
secure
}
},
{ status: 400 }
);
}
} catch (error) {
console.error('Error testing connection:', error);
return NextResponse.json(
{
error: 'Failed to test connection',
details: error instanceof Error ? error.message : 'Unknown error'
},
{ status: 500 }
);
}
}