Neah/lib/imap.ts
2025-04-21 14:17:50 +02:00

72 lines
1.9 KiB
TypeScript

import { ImapFlow } from 'imapflow';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
import { prisma } from '@/lib/prisma';
export async function getImapClient() {
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
throw new Error('No authenticated user');
}
const credentials = await prisma.mailCredentials.findUnique({
where: {
userId: session.user.id
}
});
if (!credentials) {
throw new Error('No mail credentials found. Please configure your email account.');
}
const client = new ImapFlow({
host: credentials.host,
port: credentials.port,
secure: true,
auth: {
user: credentials.email,
pass: credentials.password,
},
logger: false,
tls: {
rejectUnauthorized: false
}
});
await client.connect();
return client;
}
export async function moveEmails(emailIds: number[], targetFolder: string) {
const imap = await getImapClient();
const lock = await imap.getMailboxLock('INBOX');
try {
for (const id of emailIds) {
const message = await imap.fetchOne(id.toString(), { uid: true });
if (message) {
await imap.messageMove(message.uid.toString(), targetFolder);
}
}
} finally {
lock.release();
}
}
export async function markAsRead(emailIds: number[], isRead: boolean) {
const imap = await getImapClient();
const lock = await imap.getMailboxLock('INBOX');
try {
for (const id of emailIds) {
const message = await imap.fetchOne(id.toString(), { uid: true });
if (message) {
if (isRead) {
await imap.messageFlagsAdd(message.uid.toString(), ['\\Seen'], { uid: true });
} else {
await imap.messageFlagsRemove(message.uid.toString(), ['\\Seen'], { uid: true });
}
}
}
} finally {
lock.release();
}
}