diff --git a/lib/nodemailer/index.ts b/lib/nodemailer/index.ts new file mode 100644 index 0000000..4dffb16 --- /dev/null +++ b/lib/nodemailer/index.ts @@ -0,0 +1,102 @@ +'use server' + +import { EmailContent, EmailProductInfo } from '@/types'; +import nodemailer from 'nodemailer'; + +export const Notification = { + WELCOME: 'WELCOME', + CHANGE_OF_STOCK: 'CHANGE_OF_STOCK', + LOWEST_PRICE: 'LOWEST_PRICE', + THRESHOLD_MET: 'THRESHOLD_MET' +} + +export const generateEmailBody(product: EmailProductInfo, type: NotificationType) => { + const THRESHOLD_PERCENTAGE = 40; + + const shortenTitle = 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 ${shortenTitle}`; + 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 ${shortenTitle}`; + body = ` +
+

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

+

Grab the product here now.

+
+ `; + break; + + case Notification.THRESHOLD_MET: + subject = `Discount Alert for ${shortenTitle}`; + 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); + }) +} \ No newline at end of file