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

71 lines
2.6 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 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 which USER_X owns this mail address via JSON mapping
// Format: MAIL_USER_MAPPINGS='{"email1@domain.com":"USER_0", "email2@domain.com":"USER_1"}'
const mappingsRaw = process.env.MAIL_USER_MAPPINGS || "{}";
let ownerUserKey: string | undefined = undefined;
try {
const mappings = JSON.parse(mappingsRaw);
ownerUserKey = mappings[aliciMail];
} catch (e) {
console.error("[Mail Webhook] MAIL_USER_MAPPINGS JSON ayrıştırma hatası:", e);
}
if (ownerUserKey) {
// 2. Get that USER's Telegram ID (e.g., USER_0_TELEGRAM_ID)
const tgIdKey = `${ownerUserKey}_TELEGRAM_ID`;
const targetChatId = process.env[tgIdKey];
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 ${ownerUserKey} 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 });
}
}