fix: sent emails now have unsubscription IDs instead of {unsubscribeId}

This commit is contained in:
Dorian Niemiec 2024-09-08 07:08:35 +02:00
parent 5048891b6e
commit 4a281182ec
3 changed files with 38 additions and 38 deletions

View file

@ -15,6 +15,7 @@ EMAIL_SECURE=
EMAIL_USER=
EMAIL_PASS=
EMAIL_NEWSLETTER_ADDRESS=
EMAIL_NEWSLETTER_TESTDEST=
EMAIL_CONTACT_ADDRESS=
EMAIL_CONTACT_DEST=

View file

@ -12,18 +12,27 @@ const transporter = nodemailer.createTransport({
}
});
const sendEmail = async (to: string[], subject: string, html: string) => {
const sendEmail = async (
to: { email: string; unsubscribeId: string }[],
subject: string,
html: string
) => {
for (let i = 0; i < to.length; i++) {
try {
await transporter.sendMail({
from: process.env.EMAIL_NEWSLETTER_ADDRESS,
to: to.join(", "),
to: to[i].email,
subject: subject,
html: html
html: html.replace(
/\{unsubscribeId\}/g,
encodeURIComponent(to[i].unsubscribeId)
)
});
} catch (error) {
console.error("Error sending email:", error);
throw new Error("Failed to send email");
}
}
};
export async function POST(req: NextRequest) {
@ -35,7 +44,7 @@ export async function POST(req: NextRequest) {
const collection = db.collection("subscribers");
const subscribers = await collection
.find({}, { projection: { email: 1 } })
.find({}, { projection: { email: 1, unsubscribeId: 1 } })
.toArray();
if (subscribers.length === 0) {
@ -46,17 +55,7 @@ export async function POST(req: NextRequest) {
);
}
const emails = subscribers.map((subscriber) => subscriber.email);
if (emails.length === 0) {
console.error("No email addresses found.");
return NextResponse.json(
{ message: "No email addresses found." },
{ status: 404 }
);
}
await sendEmail(emails, subject, html);
await sendEmail(subscribers as any[], subject, html ?? "No HTML specified");
return NextResponse.json({ message: "Emails sent successfully" });
} catch (error) {
console.error("Error handling POST request:", error);

View file

@ -12,10 +12,11 @@ const transporter = nodemailer.createTransport({
});
const sendEmail = async (to: string[], subject: string, html: string) => {
for (let i = 0; i < to.length; i++) {
try {
await transporter.sendMail({
from: process.env.EMAIL_NEWSLETTER_ADDRESS,
to: to.join(", "),
to: to[i],
subject: subject,
html: html
});
@ -23,17 +24,16 @@ const sendEmail = async (to: string[], subject: string, html: string) => {
console.error("Error sending email:", error);
throw new Error("Failed to send email");
}
}
};
export async function POST(req: NextRequest) {
try {
const { subject, html } = await req.json();
// add ur email here
const testEmails = [
"abhijitbhattacharjee333@gmail.com",
"test2@example.com"
];
const testEmails = process.env.EMAIL_NEWSLETTER_TESTDEST
? process.env.EMAIL_NEWSLETTER_TESTDEST.split(",")
: [];
if (testEmails.length === 0) {
console.error("No email addresses provided.");