2024-08-26 13:11:47 +02:00
|
|
|
import { NextRequest, NextResponse } from "next/server";
|
|
|
|
import nodemailer from "nodemailer";
|
|
|
|
import clientPromise from "@/lib/db";
|
|
|
|
|
|
|
|
const transporter = nodemailer.createTransport({
|
2024-09-07 11:08:25 +02:00
|
|
|
host: process.env.EMAIL_SERVER,
|
|
|
|
port: parseInt(process.env.EMAIL_PORT ? process.env.EMAIL_PORT : "25"),
|
|
|
|
secure: Boolean(process.env.EMAIL_SECURE ? process.env.EMAIL_SECURE : false),
|
2024-09-07 09:12:48 +02:00
|
|
|
auth: {
|
2024-09-07 11:08:25 +02:00
|
|
|
user: process.env.EMAIL_USER,
|
2024-09-07 09:12:48 +02:00
|
|
|
pass: process.env.EMAIL_PASS
|
|
|
|
}
|
2024-08-26 13:11:47 +02:00
|
|
|
});
|
|
|
|
|
|
|
|
const sendEmail = async (to: string[], subject: string, html: string) => {
|
2024-09-07 09:12:48 +02:00
|
|
|
try {
|
|
|
|
await transporter.sendMail({
|
2024-09-07 11:08:25 +02:00
|
|
|
from: process.env.EMAIL_NEWSLETTER_ADDRESS,
|
2024-09-07 09:12:48 +02:00
|
|
|
to: to.join(", "),
|
|
|
|
subject: subject,
|
|
|
|
html: html
|
|
|
|
});
|
|
|
|
} catch (error) {
|
|
|
|
console.error("Error sending email:", error);
|
|
|
|
throw new Error("Failed to send email");
|
|
|
|
}
|
2024-08-26 13:11:47 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
export async function POST(req: NextRequest) {
|
2024-09-07 09:12:48 +02:00
|
|
|
try {
|
|
|
|
const { subject, html } = await req.json();
|
2024-08-26 13:11:47 +02:00
|
|
|
|
2024-09-07 09:12:48 +02:00
|
|
|
const client = await clientPromise;
|
2024-09-08 05:44:44 +02:00
|
|
|
const db = client.db(process.env.MONGODB_DB);
|
2024-09-07 09:12:48 +02:00
|
|
|
const collection = db.collection("subscribers");
|
2024-08-26 13:11:47 +02:00
|
|
|
|
2024-09-07 09:12:48 +02:00
|
|
|
const subscribers = await collection
|
|
|
|
.find({}, { projection: { email: 1 } })
|
|
|
|
.toArray();
|
2024-08-26 13:11:47 +02:00
|
|
|
|
2024-09-07 09:12:48 +02:00
|
|
|
if (subscribers.length === 0) {
|
|
|
|
console.error("No subscribers found in the database.");
|
|
|
|
return NextResponse.json(
|
|
|
|
{ message: "No subscribers found." },
|
|
|
|
{ status: 404 }
|
|
|
|
);
|
|
|
|
}
|
2024-08-26 13:11:47 +02:00
|
|
|
|
2024-09-07 09:12:48 +02:00
|
|
|
const emails = subscribers.map((subscriber) => subscriber.email);
|
2024-08-26 13:11:47 +02:00
|
|
|
|
2024-09-07 09:12:48 +02:00
|
|
|
if (emails.length === 0) {
|
|
|
|
console.error("No email addresses found.");
|
|
|
|
return NextResponse.json(
|
|
|
|
{ message: "No email addresses found." },
|
|
|
|
{ status: 404 }
|
|
|
|
);
|
|
|
|
}
|
2024-08-26 13:11:47 +02:00
|
|
|
|
2024-09-07 09:12:48 +02:00
|
|
|
await sendEmail(emails, subject, html);
|
|
|
|
return NextResponse.json({ message: "Emails sent successfully" });
|
|
|
|
} catch (error) {
|
|
|
|
console.error("Error handling POST request:", error);
|
|
|
|
return NextResponse.error();
|
|
|
|
}
|
2024-08-26 13:11:47 +02:00
|
|
|
}
|