68 lines
1.7 KiB
TypeScript
68 lines
1.7 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, 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) {
|
|
await imap.messageFlagsAdd(message.uid, isRead ? ['\\Seen'] : [], { uid: true });
|
|
}
|
|
}
|
|
} finally {
|
|
lock.release();
|
|
}
|
|
}
|