284 lines
7.3 KiB
TypeScript
284 lines
7.3 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import Imap from 'imap';
|
|
import nodemailer from 'nodemailer';
|
|
import { parseEmailHeaders, decodeEmailBody } from '@/lib/email-parser';
|
|
import { cookies } from 'next/headers';
|
|
|
|
interface StoredCredentials {
|
|
email: string;
|
|
password: string;
|
|
host: string;
|
|
port: number;
|
|
}
|
|
|
|
interface Email {
|
|
id: string;
|
|
from: string;
|
|
subject: string;
|
|
date: Date;
|
|
read: boolean;
|
|
starred: boolean;
|
|
body: string;
|
|
to?: string;
|
|
}
|
|
|
|
interface ImapBox {
|
|
messages: {
|
|
total: number;
|
|
};
|
|
}
|
|
|
|
interface ImapMessage {
|
|
on: (event: string, callback: (data: any) => void) => void;
|
|
once: (event: string, callback: (data: any) => void) => void;
|
|
attributes: {
|
|
uid: number;
|
|
flags: string[];
|
|
size: number;
|
|
};
|
|
body: {
|
|
[key: string]: {
|
|
on: (event: string, callback: (data: any) => void) => void;
|
|
};
|
|
};
|
|
}
|
|
|
|
interface ImapConfig {
|
|
user: string;
|
|
password: string;
|
|
host: string;
|
|
port: number;
|
|
tls: boolean;
|
|
authTimeout: number;
|
|
connTimeout: number;
|
|
debug?: (info: string) => void;
|
|
}
|
|
|
|
function getStoredCredentials(): StoredCredentials | null {
|
|
const cookieStore = cookies();
|
|
|
|
const credentialsCookie = cookieStore.get('imap_credentials');
|
|
console.log('Retrieved credentials cookie:', credentialsCookie ? 'Found' : 'Not found');
|
|
|
|
if (!credentialsCookie?.value) {
|
|
console.log('No credentials cookie found');
|
|
return null;
|
|
}
|
|
|
|
try {
|
|
const credentials = JSON.parse(credentialsCookie.value);
|
|
console.log('Parsed credentials:', {
|
|
...credentials,
|
|
password: '***'
|
|
});
|
|
|
|
// Validate required fields
|
|
if (!credentials.email || !credentials.password || !credentials.host || !credentials.port) {
|
|
console.error('Missing required credentials fields');
|
|
return null;
|
|
}
|
|
|
|
return {
|
|
email: credentials.email,
|
|
password: credentials.password,
|
|
host: credentials.host,
|
|
port: credentials.port
|
|
};
|
|
} catch (error) {
|
|
console.error('Error parsing credentials cookie:', error);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export async function GET() {
|
|
try {
|
|
console.log('GET /api/mail called');
|
|
const credentials = getStoredCredentials();
|
|
if (!credentials) {
|
|
console.log('No credentials found in cookies');
|
|
return NextResponse.json(
|
|
{ error: 'No stored credentials found' },
|
|
{ status: 401 }
|
|
);
|
|
}
|
|
|
|
console.log('Using credentials:', {
|
|
...credentials,
|
|
password: '***'
|
|
});
|
|
|
|
const imap = new Imap({
|
|
user: credentials.email,
|
|
password: credentials.password,
|
|
host: credentials.host,
|
|
port: credentials.port,
|
|
tls: true,
|
|
tlsOptions: { rejectUnauthorized: false },
|
|
authTimeout: 30000,
|
|
connTimeout: 30000
|
|
});
|
|
|
|
return new Promise((resolve) => {
|
|
const emails: Email[] = [];
|
|
|
|
imap.once('ready', () => {
|
|
imap.openBox('INBOX', false, (err, box) => {
|
|
if (err) {
|
|
imap.end();
|
|
resolve(NextResponse.json({ error: 'Failed to open inbox' }, { status: 500 }));
|
|
return;
|
|
}
|
|
|
|
const total = box.messages.total;
|
|
const start = Math.max(1, total - 19); // Get last 20 emails
|
|
|
|
if (total === 0) {
|
|
imap.end();
|
|
resolve(NextResponse.json({ emails: [], mailUrl: null }));
|
|
return;
|
|
}
|
|
|
|
const f = imap.seq.fetch(`${start}:${total}`, {
|
|
bodies: ['HEADER.FIELDS (FROM TO SUBJECT DATE)', 'TEXT'],
|
|
struct: true
|
|
});
|
|
|
|
f.on('message', (msg) => {
|
|
const email: any = {
|
|
id: '',
|
|
from: '',
|
|
subject: '',
|
|
date: new Date(),
|
|
read: true,
|
|
starred: false,
|
|
body: '',
|
|
to: ''
|
|
};
|
|
|
|
msg.on('body', (stream, info) => {
|
|
let buffer = '';
|
|
stream.on('data', (chunk) => {
|
|
buffer += chunk.toString('utf8');
|
|
});
|
|
stream.on('end', () => {
|
|
if (info.which === 'HEADER.FIELDS (FROM TO SUBJECT DATE)') {
|
|
const headers = Imap.parseHeader(buffer);
|
|
email.from = headers.from?.[0] || '';
|
|
email.to = headers.to?.[0] || '';
|
|
email.subject = headers.subject?.[0] || '(No subject)';
|
|
email.date = new Date(headers.date?.[0] || Date.now());
|
|
} else {
|
|
email.body = buffer;
|
|
}
|
|
});
|
|
});
|
|
|
|
msg.once('attributes', (attrs) => {
|
|
email.id = attrs.uid;
|
|
email.read = attrs.flags?.includes('\\Seen') || false;
|
|
email.starred = attrs.flags?.includes('\\Flagged') || false;
|
|
});
|
|
|
|
msg.once('end', () => {
|
|
emails.push(email);
|
|
});
|
|
});
|
|
|
|
f.once('error', (err) => {
|
|
console.error('Fetch error:', err);
|
|
imap.end();
|
|
resolve(NextResponse.json({ error: 'Failed to fetch emails' }, { status: 500 }));
|
|
});
|
|
|
|
f.once('end', () => {
|
|
imap.end();
|
|
resolve(NextResponse.json({
|
|
emails: emails.sort((a, b) => b.date.getTime() - a.date.getTime()),
|
|
mailUrl: null
|
|
}));
|
|
});
|
|
});
|
|
});
|
|
|
|
imap.once('error', (err) => {
|
|
console.error('IMAP error:', err);
|
|
resolve(NextResponse.json({ error: 'IMAP connection error' }, { status: 500 }));
|
|
});
|
|
|
|
imap.connect();
|
|
});
|
|
} catch (error) {
|
|
console.error('Error in mail API:', error);
|
|
return NextResponse.json(
|
|
{ error: error instanceof Error ? error.message : 'Unknown error' },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|
|
|
|
export async function POST(request: Request) {
|
|
try {
|
|
const credentials = getStoredCredentials();
|
|
if (!credentials) {
|
|
return NextResponse.json(
|
|
{ error: 'No stored credentials found' },
|
|
{ status: 401 }
|
|
);
|
|
}
|
|
|
|
let body;
|
|
try {
|
|
body = await request.json();
|
|
} catch (error) {
|
|
return NextResponse.json(
|
|
{ error: 'Invalid JSON in request body' },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
const { to, subject, body: emailBody, attachments } = body;
|
|
|
|
if (!to || !subject || !emailBody) {
|
|
return NextResponse.json(
|
|
{ error: 'Missing required fields: to, subject, or body' },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
const transporter = nodemailer.createTransport({
|
|
host: credentials.host,
|
|
port: credentials.port,
|
|
secure: true,
|
|
auth: {
|
|
user: credentials.email,
|
|
pass: credentials.password,
|
|
},
|
|
});
|
|
|
|
const mailOptions = {
|
|
from: credentials.email,
|
|
to,
|
|
subject,
|
|
text: emailBody,
|
|
attachments: attachments || [],
|
|
};
|
|
|
|
const info = await transporter.sendMail(mailOptions);
|
|
console.log('Email sent:', info.messageId);
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
messageId: info.messageId,
|
|
message: 'Email sent successfully'
|
|
});
|
|
} catch (error) {
|
|
console.error('Error sending email:', error);
|
|
return NextResponse.json(
|
|
{
|
|
error: error instanceof Error ? error.message : 'Failed to send email',
|
|
details: error instanceof Error ? error.stack : undefined
|
|
},
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
} |