Files
webmailserver/app/api/webhooks/mail/route.ts
2026-05-14 14:57:15 +03:00

64 lines
2.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
/**
* app/api/webhooks/mail/route.ts
*
* Webhook endpoint for incoming mail notifications.
* Uses Prisma to look up user mappings in the database.
*/
export async function POST(req: NextRequest) {
try {
const data = await req.json();
// Extract basic info from the incoming payload
const aliciMail = (data.to || data.rcpt || "").toLowerCase().trim();
const sender = data.from || "Bilinmiyor";
const subject = data.subject || "(Konu Yok)";
console.log(`[Mail Webhook] Yeni mail geldi: ${sender} -> ${aliciMail}`);
// 1. Find mapping in database
const mapping = await prisma.mailboxMapping.findUnique({
where: { email: aliciMail },
include: { user: true },
});
if (mapping?.user) {
const { user } = mapping;
const targetChatId = user.telegramId;
if (targetChatId && process.env.TELEGRAM_BOT_TOKEN) {
const message = `🔔 *Yeni Mail Geldi!*\n\n📧 *Alıcı:* ${aliciMail}\n👤 *Gönderen:* ${sender}\n📝 *Konu:* ${subject}`;
const telegramUrl = `https://api.telegram.org/bot${process.env.TELEGRAM_BOT_TOKEN}/sendMessage`;
const res = await fetch(telegramUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
chat_id: targetChatId,
text: message,
parse_mode: "Markdown",
}),
});
if (!res.ok) {
const errorText = await res.text();
console.error(`[Mail Webhook] Telegram API hatası: ${res.status} ${errorText}`);
} else {
console.log(`[Webhook] Bildirim ${user.email} kullanıcısına (ID: ${targetChatId}) gönderildi.`);
}
}
} else {
console.log(`[Webhook] Sahibi bilinmeyen veya eşleşmeyen mail: ${aliciMail}`);
}
return NextResponse.json({ status: "ok" });
} catch (error: any) {
console.error(`[Mail Webhook] Hata: ${error.message}`);
return NextResponse.json({ error: "İşlem başarısız" }, { status: 500 });
}
}