'use server' import { EmailContent, EmailProductInfo, NotificationType } from '@/types'; import nodemailer from 'nodemailer' const Notification = { WELCOME: 'WELCOME', CHANGE_OF_STOCK: 'CHANGE_OF_STOCK', LOWEST_PRICE: 'LOWEST_PRICE', THRESHOLD_MET: 'THRESHOLD_MET' } export async function generateEmailBody( product: EmailProductInfo, type: NotificationType ) { const THRESHOLD_PERCENTAGE = 40; // Shorten the product title const shortenedTitle = product.title.length > 20 ? `${product.title.substring(0, 20)}...` : product.title; let subject = ""; let body = ""; switch (type) { case Notification.WELCOME: subject = `Welcome to Price Tracking for ${shortenedTitle}`; body = `

Welcome to PriceWise 🚀

You are now tracking ${product.title}.

Here's an example of how you'll receive updates:

${product.title} is back in stock!

We're excited to let you know that ${product.title} is now back in stock.

Don't miss out - buy it now!

Product Image

Stay tuned for more updates on ${product.title} and other products you're tracking.

`; break; case Notification.CHANGE_OF_STOCK: subject = `${shortenedTitle} is now back in stock!`; body = `

Hey, ${product.title} is now restocked! Grab yours before they run out again!

See the product here.

`; break; case Notification.LOWEST_PRICE: subject = `Lowest Price Alert for ${shortenedTitle}`; body = `

Hey, ${product.title} has reached its lowest price ever!!

Grab the product here now.

`; break; case Notification.THRESHOLD_MET: subject = `Discount Alert for ${shortenedTitle}`; body = `

Hey, ${product.title} is now available at a discount more than ${THRESHOLD_PERCENTAGE}%!

Grab it right away from here.

`; break; default: throw new Error("Invalid notification type."); } return { subject, body }; } const transporter = nodemailer.createTransport({ pool: true, service: 'hotmail', port: 2525, auth: { user: 'javascriptmastery@outlook.com', pass: process.env.EMAIL_PASSWORD, }, maxConnections: 1 }) export const sendEmail = async (emailContent: EmailContent, sendTo: string[]) => { const mailOptions = { from: 'javascriptmastery@outlook.com', to: sendTo, html: emailContent.body, subject: emailContent.subject, } transporter.sendMail(mailOptions, (error: any, info: any) => { if (error) return console.log(error); console.log('Email sent: ', info); }) }