diff --git a/src/routes/emailAsUser.ts b/src/routes/emailAsUser.ts index 9f8bf1d..45693b3 100644 --- a/src/routes/emailAsUser.ts +++ b/src/routes/emailAsUser.ts @@ -4,6 +4,11 @@ import { FastifyInstance } from "fastify"; import {sendMailAsUser} from "../utils/emailengine"; import {encrypt, decrypt} from "../utils/crypt" import {secrets} from "../utils/secrets"; +// @ts-ignore +import MailComposer from 'nodemailer/lib/mail-composer/index.js' + +import {ImapFlow} from "imapflow" + export default async function emailAsUserRoutes(server: FastifyInstance) { // Create E-Mail Account @@ -164,11 +169,14 @@ export default async function emailAsUserRoutes(server: FastifyInstance) { smtp_host: string smtp_port: number smtp_ssl: boolean + imap_host: string + imap_port: number + imap_ssl: boolean } // @ts-ignore const { data, error } = await server.supabase .from("user_credentials") - .select("id, email_encrypted,password_encrypted, smtp_host_encrypted, smtp_port, smtp_ssl, user_id, tenant_id") + .select("id, email_encrypted,password_encrypted, smtp_host_encrypted, smtp_port, smtp_ssl,imap_host_encrypted,imap_port, imap_ssl, user_id, tenant_id") .eq("id", body.account) .eq("tenant_id", req.user.tenant_id) .eq("type", "mail") @@ -197,7 +205,7 @@ export default async function emailAsUserRoutes(server: FastifyInstance) { }, }) - const info = await transporter.sendMail({ + const message = { from: accountData.email, to: body.to, cc: body.cc ? body.cc : undefined, @@ -206,8 +214,43 @@ export default async function emailAsUserRoutes(server: FastifyInstance) { html: body.html ? body.html : undefined, text: body.text, attachments: body.attachments ? body.attachments : undefined, + } + + + const info = await transporter.sendMail(message) + + const imapClient = new ImapFlow({ + host: accountData.imap_host, + port: accountData.imap_port, + secure: accountData.imap_ssl, + auth: { + user: accountData.email, + pass: accountData.password, + }, + logger: false }) + await imapClient.connect() + + const mail = new MailComposer(message) + + const raw = await mail.compile().build() // → Buffer mit kompletter MIME + + + for await (const mailbox of await imapClient.list()) { + // mailbox.flags enthält z. B. ['\\Sent', '\\HasChildren'] + console.log(mailbox.specialUse) + if (mailbox.specialUse == '\\Sent') { + console.log('📨 Sent folder gefunden:', mailbox.path) + await imapClient.mailboxOpen(mailbox.path) + + await imapClient.append(mailbox.path, raw, ['\\Seen']) + + await imapClient.logout() + + break + } + } if(info.response.includes("OK")){ reply.send({success: true}) @@ -217,6 +260,7 @@ export default async function emailAsUserRoutes(server: FastifyInstance) { } catch (err) { + console.log(err) reply.code(500).send({ error: "Failed to send E-Mail as User" }) } })