diff --git a/lib/services/email-service.ts b/lib/services/email-service.ts index 06772588..f8a735e9 100644 --- a/lib/services/email-service.ts +++ b/lib/services/email-service.ts @@ -754,4 +754,88 @@ export async function getMailboxes(client: ImapFlow): Promise { // Return default folders on error return ['INBOX', 'Sent', 'Drafts', 'Trash', 'Junk']; } +} + +/** + * Test IMAP and SMTP connections for an email account + */ +export async function testEmailConnection(credentials: EmailCredentials): Promise<{ + imap: boolean; + smtp?: boolean; + error?: string; + folders?: string[]; +}> { + console.log('Testing connection with:', { + ...credentials, + password: '***' + }); + + // Test IMAP connection + try { + console.log(`Testing IMAP connection to ${credentials.host}:${credentials.port} for ${credentials.email}`); + const client = new ImapFlow({ + host: credentials.host, + port: credentials.port, + secure: credentials.secure ?? true, + auth: { + user: credentials.email, + pass: credentials.password, + }, + logger: false, + tls: { + rejectUnauthorized: false + } + }); + + await client.connect(); + const folders = await getMailboxes(client); + await client.logout(); + + console.log(`IMAP connection successful for ${credentials.email}`); + console.log(`Found ${folders.length} folders:`, folders); + + // Test SMTP connection if SMTP settings are provided + let smtpSuccess = false; + if (credentials.smtp_host && credentials.smtp_port) { + try { + console.log(`Testing SMTP connection to ${credentials.smtp_host}:${credentials.smtp_port}`); + const transporter = nodemailer.createTransport({ + host: credentials.smtp_host, + port: credentials.smtp_port, + secure: credentials.smtp_secure ?? false, + auth: { + user: credentials.email, + pass: credentials.password, + }, + tls: { + rejectUnauthorized: false + } + }); + + await transporter.verify(); + console.log(`SMTP connection successful for ${credentials.email}`); + smtpSuccess = true; + } catch (smtpError) { + console.error(`SMTP connection failed for ${credentials.email}:`, smtpError); + return { + imap: true, + smtp: false, + error: `SMTP connection failed: ${smtpError instanceof Error ? smtpError.message : 'Unknown error'}`, + folders + }; + } + } + + return { + imap: true, + smtp: smtpSuccess, + folders + }; + } catch (error) { + console.error(`IMAP connection failed for ${credentials.email}:`, error); + return { + imap: false, + error: `IMAP connection failed: ${error instanceof Error ? error.message : 'Unknown error'}` + }; + } } \ No newline at end of file