UNPKG

emailer-kit

Version:

emailer-kit is a versatile and easy-to-use Node.js utility that simplifies email sending using Nodemailer. With a streamlined interface, it provides a set of functions to effortlessly send HTML emails, making it an ideal toolkit for integrating email func

51 lines (50 loc) 1.45 kB
// src/index.ts import nodemailer from "nodemailer"; var validateEnvVariables = () => { const requiredEnvVariables = ["NODEMAIL_SERVICE", "NODEMAIL_EMAIL", "NODEMAIL_PASSWORD"]; for (const variable of requiredEnvVariables) { if (!process.env[variable]) { throw new Error(`Missing required environment variable: ${variable}`); } } }; var validateEmailAddress = (email) => { const emailRegex = /\S+@\S+\.\S+/; if (!emailRegex.test(email)) { throw new Error("Invalid email address"); } }; var createTransporter = () => { validateEnvVariables(); const config = { service: process.env.NODEMAIL_SERVICE, auth: { user: process.env.NODEMAIL_EMAIL, pass: process.env.NODEMAIL_PASSWORD } }; return nodemailer.createTransport(config); }; var emailer = async (emailerOptions) => { const { email, subject, htmlContent, file } = emailerOptions; validateEmailAddress(email); try { const transporterInstance = createTransporter(); const mailOptions = { from: process.env.NODEMAIL_EMAIL || "", to: email, subject, html: htmlContent, attachments: file ? [{ path: file.path, filename: file.name }] : void 0 }; const info = await transporterInstance.sendMail(mailOptions); console.log("Email sent:", info.response); return info; } catch (error) { console.error("Error sending email:", error); throw error; } }; export { emailer };