Files
webmailserver/app/api/webhooks/mail/route.ts

62 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 { getUsers } from "@/lib/users";
/**
* app/api/webhooks/mail/route.ts
*
* Webhook endpoint for incoming mail notifications (e.g. from Rspamd or Mailcow).
* Sends notifications to Telegram based on the recipient email.
*/
export async function POST(req: NextRequest) {
try {
const data = await req.json();
// Extract basic info from the incoming payload
const recipient = (data.to || data.rcpt || "").toLowerCase();
const sender = data.from || "Bilinmiyor";
const subject = data.subject || "(Konu Yok)";
console.log(`[Mail Webhook] Yeni mail geldi: ${sender} -> ${recipient}`);
const users = getUsers();
const user = users.find(u => u.email.toLowerCase() === recipient);
const targetChatId = user?.telegramId;
if (targetChatId && process.env.TELEGRAM_BOT_TOKEN) {
const message = `🔔 *Yeni Mail!*\n\n*Kimden:* ${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(`[Mail Webhook] Telegram bildirimi gönderildi: ${recipient}`);
}
} else {
if (!targetChatId) {
console.log(`[Mail Webhook] Alıcı için eşleşen Telegram ID bulunamadı: ${recipient}`);
}
if (!process.env.TELEGRAM_BOT_TOKEN) {
console.error("[Mail Webhook] TELEGRAM_BOT_TOKEN ayarlı değil!");
}
}
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 });
}
}